2011-09-07 65 views
0

sp_executesql的我寫的查詢:如何使用帶參數

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 

什麼是錯我的查詢?

我得到這個錯誤:

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

+0

你還可以分享[sp_executesql]的代碼嗎? – Dorin

+1

@Dorin請參閱:http://msdn.microsoft.com/en-us/library/ms188001.aspx –

回答

0

因爲你正在建設,其中字段更改動態查詢,這不能被正常的參數來實現。您必須使用該參數來構建查詢字符串 - 如果您可以從用戶輸入提供@Col_Select以避免SQL注入攻擊,請謹慎使用

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';