1

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 ?

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.