0

我有以下 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)

不明白是什么问题!

4

1 回答 1

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

于 2013-11-06T10:46:43.383 回答