1

我在网上搜索了这个问题,我一生都无法弄清楚为什么这会一直抛出错误,感谢您的帮助。

将 nvarchar 值 'SELECT @orderid = t.orderid FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY creationdatetime DESC) AS row FROM [intranet].[dbo].handbook_appendix_data WHERE id = ' 转换为数据类型 int。

DECLARE @sql nvarchar(500)
DECLARE @table varchar(40)
SET @table = 'handbook_section_data';
SET @table = 'handbook_appendix_data';

DECLARE @parentid INT
DECLARE @id INT
DECLARE @published INT
DECLARE @orderid INT
SET @parentid = 2
SET @id = -1
SET @published = 1

SET @sql = N'SELECT @orderid = t.orderid FROM 
(SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY creationdatetime DESC) AS row FROM [intranet].[dbo].'+@table+' WHERE id = '+@id+' AND published = '+@published+') AS t
WHERE t.published = '+@published+' AND t.row = 1';
EXEC SP_EXECUTESQL @sql, N'@orderid INT OUTPUT', @orderid = @orderid OUTPUT --Get the OrderID from ID

PRINT @orderid
4

3 回答 3

4

您需要将您的@id@publishedints 转换为 varchar

 convert(varchar(50),@published) 

IE

SET @sql = N'SELECT @orderid = t.orderid FROM 
(SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY creationdatetime DESC) AS row FROM [intranet].[dbo].'+@table+' WHERE id = '+     convert(varchar(50),@id) +' AND published = '+     convert(varchar(50),@published) +') AS t
WHERE t.published = '+convert(varchar(50), @published) +' AND t.row = 1';

一个更好的解决方案是避免字符串连接,并使用你已经在做的那样传递@idand@published参数,或者完全质疑动态 SQL 的要求?sp_executesql@orderid

于 2012-10-29T15:44:35.753 回答
2

您需要将整数变量转换为字符类型:

 ....
 WHERE id =' + cast(@id as varchar(32)) + ' AND published = ' + cast(@published as varchar(32)) + ') AS t ...
于 2012-10-29T15:44:49.183 回答
1

WHERE t.published = '+@published+' AND t.row = 1'

@published是一个int。SQL Server 已决定+必须在两个ints 之间,并尝试将字符串转换为int.

@published要阻止这种情况,请改为强制成为一个字符串 - 然后它添加两个字符串(连接):

WHERE t.published = '+CONVERT(varchar(10),@published)+' AND t.row = 1'

于 2012-10-29T15:44:50.427 回答