write a SQL Server cursor that iterates over INFORMATION\_SCHEMA.COLUMNS and write…
- User
write a SQL Server cursor that iterates over INFORMATION_SCHEMA.COLUMNS and write CREATE TABLE statements
- Assistant
Here is an example of a cursor that iterates over the INFORMATION_SCHEMA.COLUMNS view in SQL Server and generates a CREATE TABLE statement for each table in the database:
codeDECLARE @table_name AS NVARCHAR(128), @column_name AS NVARCHAR(128), @data_type AS NVARCHAR(128), @is_nullable AS BIT, @column_default AS NVARCHAR(128), @SQL AS NVARCHAR(MAX) -- Create a cursor to iterate over the columns of all tables in the database DECLARE column_cursor CURSOR FOR SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS -- Open the cursor OPEN column_cursor -- Loop through each row in the cursor FETCH NEXT FROM column_cursor INTO @table_name, @column_name, @data_type, @is_nullable, @column_default WHILE @@FETCH_STATUS = 0 BEGIN -- If this is the first column in the table, start building a CREATE TABLE statement IF @column_name = (SELECT MIN(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name) BEGIN SET @SQL = 'CREATE TABLE ' + @table_name + ' (' END -- Add this column to the CREATE TABLE statement SET @SQL = @SQL + @column_name + ' ' + @data_type + ' ' + CASE WHEN @is_nullable = 1 THEN 'NULL' ELSE 'NOT NULL' END + ' ' + CASE WHEN @column_default IS NOT NULL THEN 'DEFAULT ' + @column_default ELSE '' END + ', ' -- If this is the last column in the table, complete the CREATE TABLE statement and execute it IF @column_name = (SELECT MAX(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name) BEGIN SET @SQL = LEFT(@SQL, LEN(@SQL) - 1) + ')' EXEC sp_executesql @SQL END -- Move to the next row in the cursor FETCH NEXT FROM column_cursor INTO @table_name, @column_name, @data_type, @is_nullable, @column_default END -- Close and deallocate the cursor CLOSE column_cursor DEALLOCATE column_cursor