Technical Article

Create Table At Runtime

,

First you have to create Split function.

After that you have to create CreateTableAtRuntime Store Proc

EXEC CreateTableAtRuntime 3,'Student','ID;Name;Address', 'INT Identity(1,1);

the it will be show output as:

IF EXISTS (

        SELECT *

        FROM sys.objects

        WHERE object_id = OBJECT_ID('Student')

            AND type IN (N'U')

        )

    DROP TABLE [dbo].[Student]

GO

CREATE TABLE Student (

    ID INT IDENTITY(1, 1)

    ,NAME CHAR(100)

    ,Address CHAR(200)

    ) ON [PRIMARY]

CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))    
RETURNS @Results TABLE (ID INT IDENTITY(1,1),Items nvarchar(4000))    
AS    
BEGIN    
DECLARE @INDEX INT    
DECLARE @SLICE nvarchar(4000)    
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z    
--     ERO FIRST TIME IN LOOP    
SELECT @INDEX = 1    
WHILE @INDEX !=0    
BEGIN    
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER    
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)    
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE    
IF @INDEX !=0    
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)    
ELSE    
SELECT @SLICE = @STRING    
-- PUT THE ITEM INTO THE RESULTS SET    
INSERT INTO @Results(Items) VALUES(@SLICE)    
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING    
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)    
-- BREAK OUT IF WE ARE DONE    
IF LEN(@STRING) = 0 BREAK    
END    
RETURN    
END
------------------------------------------------------------------------
--CreateTableAtRuntime 3,'Student','ID;Name;Address', 'INT Identity(1,1); CHAR(100); CHAR(200)'  
ALTER PROCEDURE [dbo].[CreateTableAtRuntime] @NumberOfColumns INT
,@TableName VARCHAR(MAX)
,@ColumnsName VARCHAR(MAX)
,@DataType VARCHAR(MAX)
AS
BEGIN
DECLARE @COUNT INT = 1;
DECLARE @Columns VARCHAR(MAX);
DECLARE @Type VARCHAR(MAX);

IF (
@NumberOfColumns = (
SELECT COUNT(*)
FROM [dbo].[Split](@ColumnsName, ';')
)
AND @NumberOfColumns = (
SELECT COUNT(*)
FROM [dbo].[Split](@DataType, ';')
)
AND (
SELECT COUNT(*)
FROM [dbo].[Split](@ColumnsName, ';')
) = (
SELECT COUNT(*)
FROM [dbo].[Split](@DataType, ';')
)
)
BEGIN
PRINT 'IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(''' + @TableName + ''') AND type in (N''U''))'
PRINT 'DROP TABLE [dbo].[' + @TableName + ']'
PRINT 'GO'
PRINT 'CREATE TABLE  ' + @TableName + ' ('

WHILE (@COUNT <= @NumberOfColumns)
BEGIN
SELECT @Columns = items
FROM [dbo].[Split](@ColumnsName, ';')
WHERE ID = @COUNT

SELECT @Type = items
FROM [dbo].[Split](@DataType, ';')
WHERE ID = @COUNT

IF (@NumberOfColumns != @COUNT)
BEGIN
PRINT @Columns + ' ' + UPPER(@Type) + ' ,'
END
ELSE
BEGIN
PRINT @Columns + ' ' + UPPER(@Type) + ''
END

SET @COUNT = @COUNT + 1;
END

PRINT ') ON [PRIMARY]'
END
ELSE
BEGIN
PRINT 'Unexpected error occurred!'
END
END

Rate

1 (4)

You rated this post out of 5. Change rating

Share

Share

Rate

1 (4)

You rated this post out of 5. Change rating