Created
October 14, 2024 16:13
-
-
Save luisdelatorre012/1bbee080d388a2845245ad5b4f4c5a96 to your computer and use it in GitHub Desktop.
schema_alterer
This file contains hidden or 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 @SchemaName NVARCHAR(128) = 'YourSchemaName'; | |
| DECLARE @SQL NVARCHAR(MAX) = ''; | |
| -- Select all columns that have a NOT NULL constraint | |
| SELECT @SQL = @SQL + 'ALTER TABLE [' + s.name + '].[' + t.name + '] ALTER COLUMN [' + c.name + '] ' | |
| + TYPE_NAME(c.system_type_id) | |
| + CASE | |
| WHEN c.max_length = -1 THEN '(MAX)' | |
| WHEN c.system_type_id IN (231, 167) THEN '(' + CAST(c.max_length AS VARCHAR(10)) + ')' | |
| WHEN c.system_type_id IN (106, 108) THEN '(' + CAST(c.precision AS VARCHAR(10)) + ',' + CAST(c.scale AS VARCHAR(10)) + ')' -- Handle DECIMAL/NUMERIC | |
| WHEN c.system_type_id IN (61, 175, 189) THEN '' -- Skip length for DATETIME types | |
| ELSE '' | |
| END + ' NULL;' + CHAR(13) | |
| FROM sys.schemas s | |
| JOIN sys.tables t ON t.schema_id = s.schema_id | |
| JOIN sys.columns c ON c.object_id = t.object_id | |
| JOIN sys.types ty ON ty.user_type_id = c.user_type_id | |
| WHERE s.name = @SchemaName | |
| AND c.is_nullable = 0 -- Find columns that are NOT NULL | |
| AND ty.is_user_defined = 0 -- Exclude user-defined types | |
| -- Print or execute the generated SQL | |
| PRINT @SQL; | |
| -- You can uncomment the following line to actually run the script: | |
| -- EXEC sp_executesql @SQL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment