t-sql:在then语句中将数据类型varchar转换为numeric时出错

时间:2010-08-06 10:31:56

标签: tsql

我无法理解错误,因为我没有尝试将变量@FQTROQ转换为数字。

declare @FQTROQ varchar(30)
declare @FQNUTQ decimal(6,0)
set @FQTROQ = 'R-354'
set @FQNUTQ = 100

SELECT ( CASE WHEN (@FQTROQ is not null and @FQTROQ <> '')
THEN ( @FQTROQ )
ELSE ( @FQNUTQ ) END ) AS Numero_Troquel

有任何帮助吗?感谢

3 个答案:

答案 0 :(得分:4)

declare @FQTROQ varchar(30)
declare @FQNUTQ decimal(6,0)
set @FQTROQ = 'R-354'
set @FQNUTQ = 100

SELECT CASE WHEN (@FQTROQ is not null and @FQTROQ <> '')
THEN @FQTROQ
ELSE CAST(@FQNUTQ AS VARCHAR(30)) END AS Numero_Troquel

您需要将DECIMAL强制转换为VARCHAR,以便CASE语句的输出具有相同的输出值。

答案 1 :(得分:0)

你需要这样做:

SELECT ( CASE WHEN (@FQTROQ is not null and @FQTROQ <> '')
THEN ( @FQTROQ )
ELSE ( CAST(@FQNUTQ AS VARCHAR(30))) END ) AS Numero_Troquel

因为列的返回值需要匹配,SQL Server会尝试将VARCHAR转换为NUMERIC,而不是相反,这是您可能想要的。

该命名约定是什么,顺便说一下?

答案 2 :(得分:0)

这是因为你有2个不同类型的变量,即使你只是试图将其中一个值作为“Numero_Troquel”返回,它们也必须是兼容的类型。它正在尝试将@FQTROQ变量转换为DECIMAL。

您需要这样做:

SELECT ( CASE WHEN (@FQTROQ is not null and @FQTROQ <> '')
THEN ( @FQTROQ )
ELSE ( CAST(@FQNUTQ AS VARCHAR(30)) ) END ) AS Numero_Troquel

... OR

IF (@FQTROQ is not null and @FQTROQ <> '')
    SELECT @FQTROQ AS Numero_Troquel -- this will return as a VARCHAR
ELSE
    SELECT @FQNUTQ AS Numero_Troquel -- this will return as a DECIMAL