【发布时间】:2016-03-31 20:15:39
【问题描述】:
在下面的查询中,我尝试使用在 SQL Server 2012 中由 sp_executesql 执行的动态查询来设置 @productsExist 的值。问题是即使表 @tableName 存在并包含记录,动态查询执行后productsExist的值始终为null。
问题:为什么即使表存在且有记录,@productsExist 的查询也会返回 null?
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
【问题讨论】:
标签: sql-server-2012 dynamic-sql sp-executesql