使用sp_executesql的DynamicSQL错误



我在以下存储过程中不断收到错误。我使用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]"。

感谢

您可能需要像表名一样将项目数放入字符串中SET@SQL=N选择TOP'+Convert(varchar(10),@numberOfItems)+'*from'+@tableName+N',其中Active=1 AND BeingProcessed=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行受影响)

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

相关内容

  • 没有找到相关文章

最新更新