转换失败 - nvarchar值为数据类型int

时间:2013-11-06 10:33:29

标签: c# sql stored-procedures sqlexception

我有以下sql存储过程,但c#代码捕获异常并显示以下消息:

Conversion failed when converting the nvarchar value to data type int

SQL存储过程

@byTestType int
AS
DECLARE @qry nvarchar(3000)
IF @byTestType = 4
BEGIN
    SET @qry = 'SELECT * FROM aTbl ORDER BY aCol'
END
ELSE
BEGIN
    SET @qry = 'SELECT * FROM aTbl WHERE aCol= '
    SET @qry = @qry +''''+CAST(@byTestType as varchar(3))+''''
END

EXEC sp_executesql @qry

aCol数据类型是varchar(3)

不明白是什么问题!

1 个答案:

答案 0 :(得分:0)

我做了一些研究并修改了你的演示

DECLARE @byTestType int = 1200

DECLARE @qry nvarchar(3000)

IF @byTestType = 4
BEGIN
    SET @qry = 'SELECT * FROM aTbl ORDER BY aCol'
END
ELSE
BEGIN
    SET @qry = 'SELECT * FROM aTbl WHERE aCol= '
    SET @qry = @qry +''''+CAST(@byTestType as varchar(3))+''''
END

print @qry
有趣的是输出是:

  

SELECT * FROM aTbl WHERE aCol ='*'

请修改您的行

 SET @qry = @qry +''''+CAST(@byTestType as nvarchar)+''''

请同时注意以下情况

DECLARE @byTestType int = NULL

在这种情况下,你的@qry将为NULL