Friday, March 9, 2012

Run Dynamic Query Using Stored Procedure

Hi,

I need to create a stored procedure, which needs to accept the column name and table name as input parameter,

and form the select query at the run time with the given column name and table name..

my procedure is,

CREATE PROC spTest

@.myColumn varchar(100) ,

@.myTable varchar(100)

AS

SELECT @.myColumn FROM @.myTable

GO

This one showing me the error,

stating that myTable is not declared..

..........as i need to perform this type of query for more than 10 tables.. i need the stored procedure to accept the column and table as parameters..

Plese help me?? Is it possible in stored procedure..

DECLARE @.sql as Char(500) -- or whatever length is needed
SELECT @.sql = 'SELECT ' + @.myColumn + ' FROM ' + @.myTable
EXEC(@.sql)

No comments:

Post a Comment