1

I wanted to create a table using dynamic SQL.

If I creates a table using

CREATE Table TodayTemp(id varchar(20))
DROP TABLE TodayTemp

Then there is no problem. It works fine. But problem using this is I can't create columns dynamically. Hence I tried using store create script in a variable and then finally execute them using EXEC command.

Like

Declare @CreateTableCmd varchar(max)
SET @CreateTableCmd = 'CREATE Table TodayTemp(id varchar(20))'
Exec @CreateTableCmd

But this causes an error

Msg 2812, Level 16, State 62, Line 6
Could not find stored procedure 'CREATE Table TodayTemp(id varchar(20))'.

2
  • 2
    BTW your fiddle shows nothing. Commented Sep 6, 2013 at 6:43
  • Actually Fiddel don't changes its URL till any thing done without any error. Commented Sep 6, 2013 at 7:25

3 Answers 3

5

Add parentheses around your variable when executing

Declare @CreateTableCmd varchar(max)
SET @CreateTableCmd = 'CREATE Table TodayTemp (id varchar(20))'
Exec (@CreateTableCmd)
     ^---------------^--------here

SQLFiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer. There's some additional info here: technet.microsoft.com/en-us/library/aa175921%28v=sql.80%29.aspx
1

if you want to exec your script with exec, call it like this:

Exec (@CreateTableCmd)

Another way to do this is to use sp_executesql stored procedure:

exec sp_executesql @stmt = @CreateTableCmd

there're many links comparing this two approaches:

Comments

0
Declare @CreateTableCmd varchar(max)
SET @CreateTableCmd = 'CREATE Table TodayTemp'
Exec (@CreateTableCmd)

That should do the trick

Raj

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.