Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update script for updating a table field in SQL Server from NULL to non-NULL

I have a field (say, foo) in a table in a SQL Server database that was originally defined as nullable, but new requirements indicate that this field must be non-null.

What's the best way of updating this field to non-null via an update script without deleting the contents of the table? I tried generating a script from the Design view, but fails during execution because the current contents of the table had NULL values for foo. Worse yet, if I ignored this error, it proceeds to delete all the contents of the table!

like image 678
GP. Avatar asked Nov 17 '08 22:11

GP.


People also ask

How do I change a column from NULL to NOT NULL in SQL Server?

All you need to do is to replace [Table] with the name of your table, [Col] with the name of your column and TYPE with the datatype of the column. Execute the command and you are allowed to use NULL values for the specified column. That is all it takes to switch between NULL and NOT NULL .

How do you UPDATE a column with NULL value in SQL Server?

To set a specific row on a specific column to null use: Update myTable set MyColumn = NULL where Field = Condition. This would set a specific cell to null as the inner question asks. Save this answer.

How do you UPDATE NULL values in a table?

UPDATE [table] SET [column]=0 WHERE [column] IS NULL; Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0.

How do you replace null values in SQL with text?

We can replace NULL values with a specific value using the SQL Server ISNULL Function. The syntax for the SQL ISNULL function is as follow. The SQL Server ISNULL function returns the replacement value if the first parameter expression evaluates to NULL.


1 Answers

You've got to set a value to any rows with NULL in the NULLable column before you change it to NOT NULL.

-- Clean up the data which won't comply with the schema changes
UPDATE t SET foo = 0 WHERE foo IS NULL

-- Apply the NOT NULL
ALTER TABLE t ALTER COLUMN foo int NOT NULL

-- Add a default for the future if that's what you want
ALTER TABLE t ADD CONSTRAINT t_foo_def DEFAULT 0 FOR foo
like image 60
Cade Roux Avatar answered Oct 04 '22 03:10

Cade Roux