[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 332
  • 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

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

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