1

私はこの質問をオンラインでグーグルで検索しましたが、これがエラーをスローし続けた理由を私が一生理解できなかったので、助けていただければ幸いです。

nvarchar値の変換時に変換に失敗しました'SELECT@orderid = t.orderid FROM(SELECT *、ROW_NUMBER()OVER(PARTITION BY id ORDER BY Creationdatetime DESC)AS rowFROM[intranet]。[dbo].handbook_appendix_dataWHERE id ='toデータ型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) 

すなわち

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パラメータを渡すか、動的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 is an int. SQL Server has decided that + must be between two ints, and is trying to convert the string to an int.

To stop this, force @published to be a string instead - then it's adding two strings (concatenation) instead:

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

于 2012-10-29T15:44:50.427 に答える