How to change one attribute in a table using T-SQL to allow nulls (not null --> null)? Alter table maybe?
216
votes
8 Answers
381
votes
56
votes
Yes you can use ALTER TABLE as follows:
ALTER TABLE [table name] ALTER COLUMN [column name] [data type] NULL
Quoting from the ALTER TABLE documentation:
NULLcan be specified inALTER COLUMNto force aNOT NULLcolumn to allow null values, except for columns in PRIMARY KEY constraints.
22
votes
5
votes
4
votes
1
votes
I wrote this so I could edit all tables and columns to null at once:
select
case
when sc.max_length = '-1' and st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(MAX) NULL'
when st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(' + cast(sc.max_length as varchar(4)) + ') NULL'
else
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + ' NULL'
end as query
from sys.columns sc
inner join sys.types st on st.system_type_id = sc.system_type_id
inner join sys.objects so on so.object_id = sc.object_id
where so.type = 'U'
and st.name <> 'timestamp'
order by st.name
1
votes
This is the approach to do this: -
- Check whether the table or column exists or not.
- If yes, then alter the column. e.g:-
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'DBName' AND
TABLE_SCHEMA = 'SchemaName' AND
TABLE_NAME = 'TableName' AND
COLUMN_NAME = 'ColumnName')
BEGIN
ALTER TABLE DBName.SchemaName.TableName ALTER COLUMN ColumnName [data type] NULL
END
If you don't have any schema then delete the schema line because you don't need to give the default schema.