27.4.08

Dynamically naming the table

I've got a peculiar problem to create tables with dynamic table name.

Problem statement:

Consider an employee database in which i have to create table for each employee on each date. The table name should be given dynamically at run time. I want to create based table name based on the input.

Solution statement:

Create a stored procedure with input parameters as table name.
Construct a dynamic query for creating the table.
Execute the dynamic query.


CREATE PROCEDURE TableNameAssigningProcedure
(@EmployeeTableName varchar(100))
AS
BEGIN
DECLARE @CMD nVARCHAR(100),@AppendString VARCHAR(8)
SELECT @AppendString = CONVERT(VARCHAR(8), GETDATE(), 12)
SELECT @CMD=N'CREATE TABLE '+ @EmployeeTableName+ @AppendString + '(ID INT,NAME VARCHAR(50))'
PRINT @CMD
exec SP_EXECuteSQL @CMD
END


EXEC TableNameAssigningProcedure 'SANTHI'


SELECT * FROM "Newly created table"

Regards,
Venkatesan Prabu . J

2 comments: