Dynamic SQL usage in procedure

Bandi
Posted by Bandi under Sql Server category on | Points: 40 | Views : 265
Selecting data from a table, here the table name is dynamic...

The below code doesn't work due to the dynamic table name

CREATE PROC DynamicData ( @tableName VARCHAR(100))
AS
SELECT * FROM @tableName



To overcome above limitation, we suppose to use dynamic SQL

CREATE PROCEDURE DynamicData(@tblname nvarchar(127))
AS
EXEC('SELECT *
FROM ' + @tblname + ';')

--Calling SP
EXEC DynamicData 'EMPLOYEE'
EXEC DynamicData 'DEPT'

Comments or Responses

Login to post response