Solved

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

Posted on 2010-09-21
3
303 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
3 Comments
 
LVL 58

Accepted Solution

by:
cyberkiwi earned 500 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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

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

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.
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

920 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now