Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
how to create dynamic table creation in sql server 2008 using stored procedure
Posted
Updated 19-Apr-17 3:21am

How about something like:
SQL
CREATE PROCEDURE sproc_CreateTableAtRuntime
           @TableName NVARCHAR(128)
          ,@Column1Name NVARCHAR(32)
          ,@Column1DataType NVARCHAR(32)
          ,@Column1Nullable NVARCHAR(32)

AS

DECLARE @SQLString NVARCHAR(MAX)
SET @SQString = 'CREATE TABLE ' + @TableName + '( '+ @Column1Name + ' ' + @Column1DataType + ' '+ @Column1Nullable +') ON PRIMARY '

EXEC (@SQLString)

To execute:
SQL
EXEC sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'


If need, similar discussion here.[^]

Also, refer: How to dynamically create a table using SQLServer stored procedure [^]
 
Share this answer
 
v3
Comments
_Amy 11-Oct-12 3:32am    
5!
Sandeep Mewara 13-Oct-12 1:21am    
Thanks.
Hi,

Tables can be created dynamically in following ways.

1. Dynamic SQL -- 'Need to construct query to create table'.
Note :- here you have to check whether the table is already there
or not before executing the Dynamic sql query.

2. SELECT statement

Here we have two options to create table.

a)Create table along with data

SQL
SELECT A.COL1,A.COL2... INTO NEWTABLE
         FROM EXISTINGTABLE


If you execute this query ... sql server not only creates a table
according to the SELECT criteria but also inserts the result set
of the query into the newly created table.

b)Create table with schema only

SQL
SELECT A.COL1,A.COL2... INTO NEWTABLE
FROM EXISTINGTABLE WHERE 1=0

This query creates table according to the SELECT criteria. Here
data will not be stored in newly created table.

Thank you
 
Share this answer
 
v3
U should try like that :

SQL
ALTER PROCEDURE spName(
DECLARE @tableName VARCHAR(100),@columnName VARCHAR(50),@Query VARCHAR(8000) )
BEGIN
SET @Query='CREATE TABLE '  + @tableName + '(' +@columnName + ' VARCHAR(200)'+ ')'
EXECUTE (@Query)
END
 
Share this answer
 
Comments
brahmaiah77 7-Oct-15 2:35am    
Hi ,
this is shiva,
i have already dynamic table , how can i insert into data to table using SP. please send link this mail id:- shivaiah.dantala@gmail.com
Member 4147938 6-Apr-16 9:24am    
hi myself anuj saxena Below code is good for dynamic table creation but i will provide totally dynamic code as soon as possible.....
Richard MacCutchan 6-Apr-16 10:43am    
This question is over 3 years old. Please do not post in dead questions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900