Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2010-09-21
3
Medium Priority
?
328 Views
Last Modified: 2012-05-10
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
Comment
Question by:adimit
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 58

Accepted Solution

by:
cyberkiwi earned 2000 total points
ID: 33729738
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
 
LVL 4

Expert Comment

by:timexist
ID: 33729855
0
 

Author Closing Comment

by:adimit
ID: 33729918
thank you, I was missing the parentheses around the variable name in the exec command
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are some very powerful Dynamic Management Views (DMV's) introduced with SQL 2005. The two in particular that we are going to discuss are sys.dm_db_index_usage_stats and sys.dm_db_index_operational_stats.   Recently, I was involved in a di…
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question