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

我们两清 提交于 2019-12-22 08:36:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!