954,560 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

stored procedure to delete all records from table

Is it possible to create a stored procedure to delete all records from a table (i.e. DELETE FROM ), but pass the table name to the procedure as a parameter? My desire is to have only one procedure for deleting multiple tables' records; I would simply pass in the table name as a parameter to the procedure. If this can be done, please provide examples, thanks!

spowel4
Light Poster
32 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

Yes it can be done by using dynamic SQL.

Here is a simple example:

declare @tablename varchar(20) 
declare @criteria varchar(500) 
set @tablename = 'table1' 
set @criteria = '' --you can set criteria if you wish, I'm leaving it blank, but using it in the command. 

declare @command varchar(2000) 
set @command = 'delete from ' + @tablename + ' ' + @criteria
exec(@command)


You can read more about execute here: http://msdn.microsoft.com/en-us/library/ms188332.aspx

adam_k
Practically a Posting Shark
803 posts since Jun 2011
Reputation Points: 256
Solved Threads: 149
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You