T-SQL - 如何处理SELECT如果错误逻辑

时间:2014-11-05 12:29:37

标签: sql-server tsql

我在下面有一个简单的选择声明:

SELECT Code =   Cast([Code] as int)
FROM dbo.table 

我收到错误:

  

转换nvarchar值时转换失败'?&#39>到数据类型   中间体

我想编写IFERROR或CASE语句,用一个数字替换错误,例如-9999

2 个答案:

答案 0 :(得分:4)

SELECT 
    Code = CASE 
               WHEN ISNUMERIC(Code) = 1 THEN Cast([Code] as int) 
               ELSE -9999 
    END
FROM 
    dbo.table

答案 1 :(得分:0)

SELECT Code = Cast((case when [Code] = '?' then -9999 else [Code] end) as int)
FROM dbo.table