RATE THIS ANSWER
0
Click to Vote:
0
0
AFAIK, passing table or column names as a parameter is not allowed in the context of a stored procedure, so I think dynamic SQL must be used, so the stored procedure will just be used to generate the dynamic SQL needed.
The stored procedure would look like this:
create procedure sp1
@colname varchar(400),
@tab_name varchar(50)
AS
BEGIN
DECLARE @sqlCommand varchar(1000);
SET @sqlCommand = 'SELECT * FROM ' + @tab_name + ' WHERE CompanyName = ''' + @colname + ''''
EXEC (@sqlCommand)
END
Note all the single quotes at the end. They are all needed.
You have to be very careful when using dynamic SQL as there are some big security issues with dynamic SQL. The inherited permissions which are usually in place when using stored procedures do not apply when using dynamic SQL. Because of this the account which runs the stored procedure will need SELECT rights to what ever tables the user passes in. This creates a security hole as if a hacker uses a SQL Injection attack against the front end they will have access to pull all the data from these tables.
It is much more secure to setup a separate procedure for each table that you need to select data from.
Last Answered:
Sep 17 2008 8:36 PM GMT by Mrdenny 
46795 pts.
Latest Contributors: Carlosdl
29820 pts.