我有谷歌在线这个问题,并为我的生活无法弄清楚为什么这一直在抛出错误,任何帮助表示赞赏。
转换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 ='to data type 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
答案 0 :(得分:4)
您需要将@id
和@published
整数转换为varchar
convert(varchar(50),@published)
即
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';
更好的解决方案是避免字符串连接,并使用@id
传递@published
和sp_executesql
参数,就像您已使用@orderid
一样,或者完全质疑动态SQL的要求?
答案 1 :(得分:2)
您需要将整数变量强制转换为字符类型:
....
WHERE id =' + cast(@id as varchar(32)) + ' AND published = ' + cast(@published as varchar(32)) + ') AS t ...
答案 2 :(得分:1)
WHERE t.published = '+@published+' AND t.row = 1'
@published
是int
。 SQL Server已确定+
必须介于两个int
之间,并且正在尝试将字符串转换为int
。
要停止此操作,请将@published
强制为字符串 - 然后再添加两个字符串(连接):
WHERE t.published = '+CONVERT(varchar(10),@published)+' AND t.row = 1'