简体   繁体   中英

DynamicSQL using sp_executesql Error

I keep getting an error with the following stored procedure. I had it working correctly using EXEC, then I switched to sp_executesql and I haven't been able to get it to execute. I keep getting the following error: Incorrect syntax near '@numberOfItems'.

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 is a string structured as follows: "[TABLENAME]".

Thanks

您可能需要像表名一样将项目数放入字符串中。SET @SQL = N'选择TOP'+ Convert(varchar(10),@ numberOfItems)+'* from'+ @tableName + N'活动= 1 AND正在处理= 0'

I think you can only use parameters for sp_executesql statement in positions where variables are allowed.

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)

Solution 1 (parenthesis, recommended):

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

Solution 2 (concatenation, make sure to prevent SQL injection!):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM