I'm creating a table dynamically and need to be able to use a case for the column length. if it is an int or date or whatever there is no column length, but if it's some other I need to include it in my statement.
the table I'm using to create this table contains:
column_name column_datatype column_length column_comment
firstname VARCHAR 100 Contains first name
birthday DATETIME NULL Contains birthday
the table I'm using to create this table contains:
column_name column_datatype column_length column_comment
firstname VARCHAR 100 Contains first name
birthday DATETIME NULL Contains birthday
Code:
DECLARE cur_feedcolumns CURSOR FOR
SELECT * FROM #temp_feedcolumns
OPEN cur_feedcolumns
FETCH NEXT FROM cur_feedcolumns INTO @vc_column_id, @vc_column_name, @vc_column_datatype, @vc_column_length,
@vc_column_comment, @vc_updatable, @vc_name
WHILE (@@FETCH_STATUS = 0)
BEGIN
SELECT @sql = 'EXEC (''ALTER TABLE [' + @v_listdatabase + '].dbo.' + @p_listname +
' ADD '' + @vc_column_name + @vc_column_datatype +
CASE WHEN @vc_column_length IS NULL THEN '''' ELSE ''('' + @vc_column_length + '')'' END + '' NULL'')'
PRINT @sql
EXEC sp_executesql @sql, N'@vc_column_name VARCHAR(200), @vc_column_datatype VARCHAR(20), @vc_column_length INT',
@vc_column_name, @vc_column_datatype, @vc_column_length
FETCH NEXT FROM cur_feedcolumns INTO @vc_column_id, @vc_column_name, @vc_column_datatype, @vc_column_length,
@vc_column_comment, @vc_updatable, @vc_name
END
CLOSE cur_feedcolumns
DEALLOCATE cur_feedcolumns