使用sp_executesql错误的动态SQL

时间:2012-07-17 23:04:07

标签: sql sql-server-2008 stored-procedures dynamic-sql sp-executesql

我一直在使用以下存储过程收到错误。我使用EXEC正常工作,然后我切换到sp_executesql,我无法让它执行。我一直收到以下错误:'@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是一个字符串,结构如下:“[TABLENAME]”。

由于

2 个答案:

答案 0 :(得分:4)

您可能需要以与表名相同的方式将多少项放入字符串中     SET @SQL = N'Select TOP'+ Convert(varchar(10),@ numberOfItems)+'* from'+ @tableName + N',其中Active = 1 AND BeingProcessed = 0'

答案 1 :(得分:0)

我认为你只能在允许变量的位置使用sp_executesql语句的参数。

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

@ numberOfItems'附近的语法不正确。

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

必须声明表变量" @ table"。

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

(2行(s)受影响)

解决方案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