Created
June 1, 2023 17:45
-
-
Save JosiahSiegel/673c0f8a9a0fca42150c1630a24a10c9 to your computer and use it in GitHub Desktop.
Generate scripts to change all columns in MSSQL table to allow NULL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE | |
@schema SYSNAME = '', | |
@table SYSNAME = '' | |
-- Declare variables to store column name and data type | |
DECLARE @column_name varchar(50) | |
DECLARE @data_type varchar(50) | |
-- Declare a cursor to loop through the columns of the table | |
DECLARE column_cursor CURSOR FOR | |
SELECT c.name, ty.name | |
FROM sys.columns c | |
JOIN sys.types ty ON c.user_type_id = ty.user_type_id | |
INNER JOIN sys.tables t ON c.object_id = t.object_id | |
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id | |
WHERE s.name = @schema AND t.name = @table | |
AND c.is_nullable = 0 -- Only select columns that are not null | |
-- Open the cursor and fetch the first row | |
OPEN column_cursor | |
FETCH NEXT FROM column_cursor INTO @column_name, @data_type | |
-- Loop through the rows until there are no more | |
WHILE @@FETCH_STATUS = 0 | |
BEGIN | |
-- Print a script to alter the column to allow nulls | |
PRINT 'ALTER TABLE ' + QUOTENAME(@schema) + '.' + QUOTENAME(@table) + ' ALTER COLUMN ' + QUOTENAME(@column_name) + ' ' + @data_type + ' NULL' | |
-- Fetch the next row | |
FETCH NEXT FROM column_cursor INTO @column_name, @data_type | |
END | |
-- Close and deallocate the cursor | |
CLOSE column_cursor | |
DEALLOCATE column_cursor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment