I have a problem where I have to create tables on basis of number of parameters passed in the stored procedure as follows:
----when there is one column
'CREATE TABLE [dbo].['+@table_name+'] (
['+@colname1+'] [VARCHAR](200)
) '
----when there are two column
'CREATE TABLE [dbo].['+@table_name+'] (
['+@colname1+'] [VARCHAR](200),
['+@colname2+'] [VARCHAR](200)
) ;'
----when there are three column
'CREATE TABLE [dbo].['+@table_name+'] (
['+@colname1+'] [VARCHAR](200),
['+@colname2+'] [VARCHAR](200),
['+@colname3+'] [VARCHAR](200)
) '
One way that I know of doing this is:
----when there is one column
If ((@colname1 IS NOT NULL AND LEN(@colname1) !=0))
BEGIN
'CREATE TABLE [dbo].['+@table_name+'] (
['+@colname1+'] [VARCHAR](200)
)'
END
----when there are two column
If ((@colname1 IS NOT NULL AND LEN(@colname1) !=0)
AND (@colname2 IS NOT NULL AND LEN(@colname2) !=0))
BEGIN
Drop table [dbo].['+@table_name+']
'CREATE TABLE [dbo].['+@table_name+'] (
['+@colname1+'] [VARCHAR](200),
['+@colname2+'] [VARCHAR](200)
)'
END
----when there are three column
If ((@colname1 IS NOT NULL AND LEN(@colname1) !=0)
AND (@colname2 IS NOT NULL AND LEN(@colname2) !=0)
AND (@colname3 IS NOT NULL AND 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 this way, my code becomes very lengthy. Is there any other efficient way to do this. If instead of passing values for @colname1, @colname2,@colname3 separately, I pass values in one single parmaeter @colname as @colname = 'col1,col2,col3', how can I do it?