sp_executesql 未在 SQL Server 2012 的动态 sql 查询中正确设置变量

sp_executesql not setting a variable correctly in a dynamic sql query in SQL Server 2012

在下面的查询中,我尝试使用 sp_executesql 在 SQL Server 2012 中执行的动态查询来设置 @productsExist 的值。问题是即使table @tableName存在并包含记录,执行动态查询后productsExist的值总是null

问题:为什么 @productsExist 的查询返回空值,即使 table 存在并有记录?

DECLARE @productsExist INT;
DECLARE @countQuery NVARCHAR(MAX) = 'IF OBJECT_ID(@tableName, N''U'') IS NOT NULL 
                     begin  select top(1) @productsExist = 1  from ' + @tableName + ' end';

EXECUTE sp_executesql @countQuery, N'@tableName varchar(500),@productsExist INT',
              @tableName = @tableName,
              @productsExist = @productsExist;

select @productsExist as ProductsExist--returns always a NULL value for ProductsExist

您需要将 @productsExist 参数声明为 OUTPUT:

[ OUT | OUTPUT ]

Indicates that the parameter is an output parameter

DECLARE @productsExist INT
        ,@tableName SYSNAME = 'tab';

DECLARE @countQuery NVARCHAR(MAX) = 
N'IF OBJECT_ID(@tableName, N''U'') IS NOT NULL 
  begin  select top(1) @productsExist = 1  from ' + QUOTENAME(@tableName) + ' end';

EXECUTE dbo.sp_executesql 
        @countQuery,
        N'@tableName SYSNAME ,@productsExist INT OUTPUT',     -- here
        @tableName = @tableName,
        @productsExist = @productsExist OUTPUT;               -- here

SELECT @productsExist as ProductsExist;

SqlFiddleDemo


如果指定的 table 中没有记录,则 @productsExist 将 return NULL。如果您想要 1 表示现有记录,0 表示没有记录,请使用:

DECLARE @countQuery NVARCHAR(MAX) = 
N'IF OBJECT_ID(@tableName, N''U'') IS NOT NULL 
  BEGIN
    IF EXISTS (SELECT 1 FROM '+ QUOTENAME(@tableName) + ')
       SELECT @productsExist = 1
    ELSE 
       SELECT @productsExist = 0
  END'; 

SqlFiddleDemo2

结果:

table not exists          => NULL
table exists no records   => 0
table exists >= 1 records => 1