Need an efficient way to perform the given SQL query in SQL Server, stored procedure -
i have problem have create tables on basis of number of parameters passed in stored procedure follows:
----when there 1 column 'create table [dbo].['+@table_name+'] ( ['+@colname1+'] [varchar](200) ) ' ----when there 2 column 'create table [dbo].['+@table_name+'] ( ['+@colname1+'] [varchar](200), ['+@colname2+'] [varchar](200) ) ;' ----when there 3 column 'create table [dbo].['+@table_name+'] ( ['+@colname1+'] [varchar](200), ['+@colname2+'] [varchar](200), ['+@colname3+'] [varchar](200) ) '
one way know of doing is:
----when there 1 column if ((@colname1 not null , len(@colname1) !=0)) begin 'create table [dbo].['+@table_name+'] ( ['+@colname1+'] [varchar](200) )' end ----when there 2 column if ((@colname1 not null , len(@colname1) !=0) , (@colname2 not null , len(@colname2) !=0)) begin drop table [dbo].['+@table_name+'] 'create table [dbo].['+@table_name+'] ( ['+@colname1+'] [varchar](200), ['+@colname2+'] [varchar](200) )' end ----when there 3 column if ((@colname1 not null , len(@colname1) !=0) , (@colname2 not null , len(@colname2) !=0) , (@colname3 not null , len(@colname3) !=0)) begin drop table [dbo].['+@table_name+'] 'create table [dbo].['+@table_name+'] ( ['+@colname1+'] [varchar](200), ['+@colname2+'] [varchar](200), ['+@colname3+'] [varchar](200) ) ' end
by using way, code becomes lengthy. there other efficient way this. if instead of passing values @colname1, @colname2,@colname3 separately, pass values in 1 single parmaeter @colname @colname = 'col1,col2,col3', how can it?
it possible use dynamic sql , comma delimited parameter column names, though wrote in comment, bad idea, , recommend re-think approach. using "xml split string technique" , quotename
minimize sql injection hazard:
create procedure stpcreatetabledynamically ( @table_name sysname, @column_names nvarchar(max) ) declare @sql nvarchar(max) select @sql = 'create table [dbo].' + quotename('zzz_'+ @table_name) +' (' select @sql = @sql + quotename(split.a.value('.', 'varchar(100)')) + ' [varchar](200),' (select cast ('<m>' + replace(@column_names, ',', '</m><m>')+ '</m>' xml) data) cross apply data.nodes ('/m') split(a); select @sql = left(@sql, len(@sql) - 1) + ') on [zzz_fg];' print @sql --exec(@sql) go
usage:
exec stpcreatetabledynamically 'mytable', 'column1,col2,col3'
output:
create table [dbo].[zzz_mytable] ([column1] [varchar](200),[col2] [varchar](200),[col3] [varchar](200)) on [zzz_fg];
once see output ok, can unremark exec
line , delete print
line.
Comments
Post a Comment