Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have a stored procedure as below:

SQL
USE [MashtiHasanShoppingDB]
GO
/****** Object:  StoredProcedure [dbo].[Del_Users]    Script Date: 9/12/2015 1:57:45 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Del_Users]
@UserID int
AS
BEGIN
	DELETE FROM Users where UserID = @UserID
END


Now, I want to have this stored procedure working for other table's. I shouldn't write the same code over and over for one database.
I want it to take the table name as an parameter, something like:
SQL
ALTER PROCEDURE [dbo].[Del_Users]
@UserID int,
@Table_name nvarcher(50)
AS
BEGIN
	DELETE FROM @Table_name where UserID = @UserID
END


But i don't know how to do it.

I'd be grateful of your help,
Thanks.
Posted

By creating a dynamic sql statement you will be able to build and run the query at runtime.

This should do the trick. First run the stored procedure and check the output from the print command. When you are confident that all is okay, comment out the print command and uncomment the exec command:

ALTER PROCEDURE [dbo].[Del_Users]
@UserID int,
@Table_name nvarcher(50)
AS
BEGIN
	
	declare @cmd nvarchar(max) = ''
	set @cmd += N' DELETE FROM ' + @Table_name + ' where UserID = ' @UserID
    print @cmd
	--exec sys.sp_executesql @cmd

	
END
 
Share this answer
 
v2
You can do it - but it's a pain:
SQL
DECLARE @Command NVARCHAR(MAX)
SET @Command = 'DELETE FROM ' + @Table_name + ' WHERE UserId = ' + @UserID
EXEC(@Command)


It's also risky: it leave you open to SQL Injection attacks if @UserID is changed to a string.

Personally? I wouldn't do it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900