How to change one attribute in a table using T-SQL to allow nulls (not null --> null)? Alter table maybe?
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:
NULL
can be specified inALTER COLUMN
to force aNOT NULL
column to allow null values, except for columns in PRIMARY KEY constraints.
-- replace NVARCHAR(42) with the actual type of your column
ALTER TABLE your_table
ALTER COLUMN your_column NVARCHAR(42) NULL
So the simplest way is,
alter table table_name change column_name column_name int(11) NULL;
For MySQL, MariaDB
ALTER TABLE [table name] MODIFY COLUMN [column name] [data type] NULL
Use MODIFY COLUMN
instead of ALTER COLUMN
.
ALTER TABLE is right:
ALTER TABLE MyCustomers ALTER COLUMN CompanyName VARCHAR(20) NULL
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