Reputation: 2930
I have @db_out = 'aux.dbo.some_table_name'
, and I don't know how to drop , create based on that variable like :
IF OBJECT_ID(@db_out) IS NOT NULL DROP TABLE "@db_out" - not working
CREATE TABLE "@db_out" .... etc
it creates master.dbo.@dbo_out
How can I use that variable to create that table or verify it and drop it ?
Upvotes: 1
Views: 226
Reputation: 86706
You need to write dynamic SQL.
SET @sql = 'IF OBJECT_ID(@db_out) IS NOT NULL DROP TABLE ' + @db_out + '; '
SET @sql = @sql + 'CREATE TABLE ' + @db_out + ' (...)'
EXEC(@sql)
Upvotes: 1
Reputation: 19346
You will have to build the statement in varchar variable and execute it:
declare @strSql as varchar(max)
IF OBJECT_ID(@db_out) IS NOT NULL
BEGIN
EXEC ('DROP TABLE [' + @db_out + ']')
END
set @strSql = 'CREATE TABLE [' + @db_out + '] (' -- Etc
EXEC (@strSql)
Upvotes: 3