2017-10-04 84 views
1

我有這個疑問導致這個錯誤:錯誤SQL條件的情況下未能轉換

Failed when converting the varchar value ')' to data type tinyint.

這是我的代碼有問題:

select 
    case t.name 
     when 'numeric' 
      then cast (c.precision + ')' as varchar(100)) 
    end 
from 
    sys.columns c 
inner join 
    sys.types t ON t.user_type_id = c.user_type_id 
inner join 
    sys.tables tb on tb.name = 'EX_EMPLOYEE' 
where 
    c.name = 'B_CODE' and tb.object_id = c.object_id 

回答

2

也許(如2012+)

case t.name when 'numeric' then concat(c.precision,')') end 
1

您也可以試試這個:

select 
    case t.name when 'numeric' then cast (c.precision as varchar(100)) +')' end 

as c.precision顯然是tinyint數據類型。當您添加不同的數據類型時,它在c.precision +')'上失敗。

1

將你的連接移動到CAST之外,還改變了JOINWHERE的參數。

SELECT CASE WHEN t.name = 'numeric' 
      THEN CAST(c.precision AS varchar(100)) +')' 
     END 
FROM sys.columns c 
INNER JOIN sys.types t ON t.user_type_id = c.user_type_id 
INNER JOIN sys.tables tb ON tb.object_id = c.object_id 
WHERE c.name = 'B_CODE' 
AND tb.name = 'EX_EMPLOYEE' 
1

我想你需要在連接它們之前將tinyint值轉換爲varchar。像這樣(或者只是將c.precision轉換爲varchar(100),然後添加')':

select 
    case t.name when 'numeric' then cast (cast (c.precision as varchar(10)) +')' as varchar(100)) 
    end 

    from sys.columns c inner JOIN sys.types t ON t.user_type_id = 
    c.user_type_id 
    inner join sys.tables tb on tb.name='EX_EMPLOYEE' where c.name = 
    'B_CODE' and tb.object_id = c.object_id