I have written a stored procedure where a table name and database name collect
using cursor from different two tables.
But my problem is when I run a query to find out a table exists in a database or not, then show a error.
Now how can I run the query and store output into a variable?
Declare @table_exist nvarchar(200),@val1 nvarchar(200),@return1 nvarchar(200);
SET @table_exist=
'SELECT 1 FROM '+@db_name+'.sys.tables
where name='+@table_name+'';
EXEC sp_executesql @table_exist,@return1 OUTPUT;
select @return1;
ERROR:
Invalid column name 'table name'
You should use quotename when building dynamic query:
When facing such an error the best would be to
print @table_existsand see what is actually built.I haven’t looked properly at your query. You are missing apostrophes:
UPDATE:
When using output variable you should set it in a query:
To prevent result set from returning to client, create temporary table and insert result set into it. In this case this will leave only one result set, the result of
select @return1: