Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 using sp_executeSQL to create a DDL statement

Author  Topic 

Bex
Aged Yak Warrior

580 Posts

Posted - 2008-12-16 : 07:41:35
I need to dynamically create a set of tables. I am using a template definition to define the columns. I was creating @SQL and using exec (@SQL).

Is there a way to use sp_executesql instead?

e.g.
declare @sql nvarchar(max), @params nvarchar(max), @count int

set @sql = 'select * from template.@header where ID = @count'
set @params = '@count int, @header nvarchar(100)'

exec sp_executesql @sql, @params, @count = 1, @header = 'Header'

I just get the error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '@header'.

Does the optimiser parse the statement before replacing the paramatized values?

Thanks

Hearty head pats

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-16 : 07:50:40
[code]
declare @sql nvarchar(max), @params nvarchar(max), @count int

set @sql = 'select * from template.'+@header+' where ID = '+@count
set @params = '@count int, @header nvarchar(100)'

exec sp_executesql @sql, @params, @count = 1, @header = 'Header'
[/code]
Go to Top of Page

Bex
Aged Yak Warrior

580 Posts

Posted - 2008-12-16 : 08:21:43
THANKS AGAIN

Hearty head pats
Go to Top of Page
   

- Advertisement -