简体   繁体   中英

SQL Server: How can I check to see if a field has a “NULL” or “NOT NULL” constraint in place?

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.

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM