开发者

How using sp_executesql with parameters

I wrote a query:

DECLARE @Col_Select NVARCHAR(10);
SET @Col_Select = N'[od.orderID]';

DECLARE @Query NVARCHAR(4000);
SET @Query = N'SELECT quantity, COUNT(o.orderID) FROM orders o LEFT OUTER JOIN [order details] od ON o.orderid = @Col_Select group by od.quantity';

EXEC sp_executesql @Query,@Col_Select

What is wrong with my query?

I get th开发者_如何学编程is error:

Incorrect syntax near 'od.orderI)SELECT quantity,COUNT(o.orderID) FROM orders o LEFT OUTER JOIN [order details'.


Because you are building a dynamic query where the fields change, this can't be done by normal parameters. You'll have to use the parameter to build up the string of the query - be very careful if you can supply @Col_Select from user input to avoid SQL Injection attacks!

SET @Query=N'SELECT quantity,COUNT(o.orderID) FROM orders o LEFT OUTER JOIN [order details] od ON o.orderid = ' + @Col_Select + ' group by od.quantity';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜