Reputation: 1064
Could anyone please let me know if there is a way to programatically determine if a Micorosft SQL Server database table field has a NULL or NOT NULL constraint in place? I need this so that I can deploy a patch that is safe to be re-runnable. So I'm after something like this (conceptual/pseudo-code):
IF (my_table COLUMN end_date HAS CONSTRAINT OF 'NOT NULL') ALTER TABLE my_table ALTER COLUMN end_date DATETIME NULL
So I want to change my_table.end_date from 'NOT NULL' to 'NULL' if it hasn't already been changed. I'm just unsure of what the part in the brackets should be.
I know how to interrogate dbo.sysobjects for things like existing fields, existing foreign key constraints and the like (there are a few threads already on that), but I'm just not sure how to check specifically for a NULL/NOT NULL field constraint. Any help would be much appreciated.
Upvotes: 4
Views: 2654
Reputation: 5425
If you're on SQL Server 2005+, this returns "NO" if there is a NOT NULL constraint:
SELECT IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tblName'
AND COLUMN_NAME = 'colName'
Upvotes: 0
Reputation: 103447
You can look at INFORMATION_SCHEMA.COLUMNS
:
if (select IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='my_table' and COLUMN_NAME='end_date') = 'NO'
begin
ALTER TABLE my_table ALTER COLUMN end_date DATETIME NULL
end
Upvotes: 4