Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create a table with dynamic columns i.e. number of columns to be defined by
user
using STORED PROCEDURE.

Let me clarify my requirement, I need to create a table (dyn_tbl) via SP whose inputs will be "number of fields".

e.g.
----------------------------------------------------------------
SQL
CREATE OR REPLACE PROCEDURE dynamic_tbl (num_fields varchar2)
AS

num_fields varchar2(25);

BEGIN

END;
/

----------------------------------------------------------------
If user inputs num_fields = 3, o/p will be;

SQL
create table dyn_tbl
(
col_1 varchar2(20);
col_2 varchar2(20);
col_3 varchar2(20);
);

*********

If user inputs num_fields = 5, o/p will be;

SQL
create table dyn_tbl
(
col_1 varchar2(20);
col_2 varchar2(20);
col_3 varchar2(20);
col_4 varchar2(20);
col_5 varchar2(20);
);


************************************************

Here the column name differ only by there last character which is based on user
requirement
.

How can I do it?
Posted
Updated 18-May-18 21:46pm

1 solution

SQL
CREATE PROCEDURE dynamic_tbl
@ColumnCount int=0
AS 
BEGIN
	Declare @ColumnName nvarchar(10)='col_'
	Declare @count int =1
	IF(@ColumnCount>0)
	BEGIN
		IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND  TABLE_NAME = 'dyn_tbl'))
		BEGIN
			
			DROP TABLE dyn_tbl
		END
		CREATE TABLE [dbo].[dyn_tbl]
		(	col_1 varchar(20)	)
		SET @count=@count +1;
		WHile(@ColumnCount>=@count) 
		BEGIN
			SET @ColumnName='col_'+CONVERT(varchar(2),@count)
			EXEC ('ALTER TABLE dyn_tbl ADD ['+@ColumnName +'] varchar(20)')
			SET @count=@count +1;
		END
	END
END
 
Share this answer
 
v2
Comments
nischalinn 22-Aug-13 8:08am    
thanks for the reply.

but I think it will be better if we create table using a loop and then execute it
rather than each time ALTERING the table according to the requirement.
Sadique KT 22-Aug-13 8:22am    
if you have another way plz post the code..

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