2

我不斷收到以下存儲過程的錯誤。我已經使用EXEC正常工作,然後我切換到sp_executesql,我一直無法執行它。我不斷收到以下錯誤:'@numberOfItems'附近的語法不正確。使用sp_executesql的DynamicSQL錯誤

ALTER PROCEDURE dbo.FetchResourcesToProcess 
(
@tableName nvarchar(MAX), 
@numberOfItems int 
) 
AS 
    BEGIN 
     DECLARE @SQL nvarchar(MAX); 
     SET NOCOUNT ON; 
     SET @SQL = N'Select TOP @numberOfItems * from ' + @tableName + N' where Active = 1 AND BeingProcessed = 0' 
     EXEC sp_executesql @SQL, N'@numberOfItems int', @numberOfItems 
    END 

表名是一個字符串,結構如下:「[TABLENAME]」。

感謝

+0

做一個選擇@SQL。獲取結果並將其複製並粘貼到SSMS中,看看是否可以執行該操作。你會得到更好的錯誤消息。 – JeffO 2012-07-17 23:11:59

+1

您需要在@numberOfItems附近放置圓括號:'N'Select TOP(@numberOfItems)* from' – 2012-07-17 23:20:27

回答

4

你可能需要將項目數串入你的表名以相同的方式 SET @SQL = N'Select TOP'+轉換(VARCHAR(10),@ numberOfItems)+ '* from'+ @tableName + N'其中Active = 1 AND BeingProcessed = 0'

+0

這就像一個魅力!謝謝一堆! – Sizzle 2012-07-17 23:10:32

0

我認爲您只能在允許變量的位置使用sp_executesql語句的參數。

use master; 
declare @numberOfItems int; 
set @numberOfItems = 2; 
Select TOP @numberOfItems * from dbo.spt_values 

Incorrect syntax near '@numberOfItems'.

use master; 
declare @table varchar(max); 
set @table = 'dbo.spt_values'; 
Select * from @table 

Must declare the table variable "@table".

use master; 
declare @numberOfItems int; 
set @numberOfItems = 2; 
Select TOP(@numberOfItems) * from dbo.spt_values 

(2 row(s) affected)

溶液1(括號,推薦):

 SET @SQL = N'Select TOP(@numberOfItems) * from ' + @tableName + N' where Active = 1 AND BeingProcessed = 0' 

解決方案2(串聯,一定要防止SQL注入!):

 SET @SQL = N'Select TOP '+cast(@numberOfItems as nvarchar(MAX))+' * from ' + @tableName + N' where Active = 1 AND BeingProcessed = 0' 
     EXEC sp_executesql @SQL