问题
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.
回答1:
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
回答2:
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'
来源:https://stackoverflow.com/questions/11129842/sql-server-how-can-i-check-to-see-if-a-field-has-a-null-or-not-null-constra