• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 334
  • Last Modified:

T-SQL sql server 2005 execute command by passing a variable

I would like to execute simple commands such as the following:

delete @tablename
insert into @tablename .......

where @tablename is a varchar  parameter I pass to the stored procedure.

How can i do this
0
adimit
Asked:
adimit
1 Solution
 
cyberkiwiCommented:
You need to generate dynamic SQL Statements.

Mandatory BIG warning : do read up on "SQL Injection" (search on Google) before you proceed if you are using dynamic SQL with user input, but it does not look like the case here.

Something like this:

create proc mySP
@tablename sysname
as
declare @sql nvarchar(max)
set @sql = 'delete ' + @tablename -- everything
exec (@sql)
set @sql = 'insert into ' + @tablename + ' (col) values (val)'
exec (@sql)
0
 
timexistCommented:
0
 
adimitAuthor Commented:
thank you, I was missing the parentheses around the variable name in the exec command
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now