Sizzle
Sizzle

Reputation: 47

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

Upvotes: 2

Views: 503

Answers (2)

jumxozizi
jumxozizi

Reputation: 649

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

Upvotes: 0

automatic
automatic

Reputation: 2737

You probably need to place number of items into the string the same way you are the table name SET @SQL = N'Select TOP ' + Convert(varchar(10),@numberOfItems) + ' * from ' + @tableName + N' where Active = 1 AND BeingProcessed = 0'

Upvotes: 4

Related Questions