In query below, I am trying to set the value of @productsExist
using a dynamic query that is executed by sp_executesql
in SQL Server 2012. The problem is that even though the table @tableName
exists and contains records, the value of productsExist
is always null
after the dynamic query is executed.
Question: Why is the query returning null for @productsExist
even when the the table exists and has records?
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