DROP TABLE table1
DROP TABLE table2
DROP PROCEDURE DynamicTableSP
USE kalyandb
CREATE TABLE table1 (id INT IDENTITY (1,1), NAME VARCHAR(20))
INSERT INTO table1 VALUES ( 'Apple')
INSERT INTO table1 VALUES ( 'BenQ')
CREATE TABLE table2 (id INT IDENTITY (1,1), NAME VARCHAR(20))
INSERT INTO table2 VALUES ('Samsung')
INSERT INTO table2 VALUES ('Sony')
CREATE PROCEDURE DynamicTableSP (@tname varchar(20)) AS
BEGIN
DECLARE @table_name VARCHAR(10)
DECLARE @sql VARCHAR(500)
SET @table_name = @tname
SET @sql = ' DECLARE @name VARCHAR(20) DECLARE db_cursor CURSOR FOR SELECT name FROM ' +@table_name + ' OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @name
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
DEALLOCATE db_cursor '
EXEC (@sql)
END
EXEC DynamicTableSP 'table1'
EXEC DynamicTableSP 'table2'
No comments: