Click here to Skip to main content
15,907,497 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to create a stored procedure to create a table where the table name and the field has to be given only during executing the procedure.? Is it possible..
Posted

Yes you can do it !!! But it is a complex thing you need to handle that. While Creation of table first you need to check the table name if exists or not. Then we need to write a dynamic sql execution query for that. Please give a try with this Idea
 
Share this answer
 
Yes you can do it, look at following code.
SQL
create PROCEDURE sproc_CreateTableAtRuntime
(
	@TableName NVARCHAR(128)
	,@Column1Name NVARCHAR(32)
	,@Column1DataType NVARCHAR(32)
	,@Column1Nullable NVARCHAR(32)
)
AS
Begin
	DECLARE @SQLString NVARCHAR(MAX)
	SET @SQLString = 'CREATE TABLE ' + @TableName + '( '+ @Column1Name + ' ' + 	@Column1DataType + ' '+ @Column1Nullable +')' 
	EXEC (@SQLString)
End


Now you can execute the store procedure as follows:
SQL
sproc_CreateTableAtRuntime 'MyTable','MyColumn1','Int','Not Null'
 
Share this answer
 
hi , this is an Example

SQL
create table myTbl1 (name nvarchar(100) not null ,family varchar(100)
primary key (name))


you can also Add Foreign Keys , ...
 
Share this answer
 
v4

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