How to find the name of not-null constraints in SQL Server

a 夏天 提交于 2019-12-24 00:28:26

问题


How can I find the name of a named not-null constraint in SQL Server? I can find check constraints, default constraints, FK constraints, PK constraints and unique constraints, but the NN constraint has eluded me.


回答1:


You can't.

Whilst the syntax does accept a name...

CREATE TABLE T
(
C INT CONSTRAINT NN NOT NULL
)

... and it is parsed and validated as a name ...

CREATE TABLE T
(
C INT CONSTRAINT NN123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 NOT NULL
)
/* The identifier that starts with 'NN1234...6' is too long. Maximum length is 128. */

... this is then ignored and isn't actually stored anywhere.

No row is added to sys.objects for these unlike other constraints. It is just stored as a bit property of the associated column rather than a constraint object.




回答2:


List columns with not-null constraint

DECLARE @Table NVARCHAR(MAX) = 'Your table name here'

SELECT
    [COLUMN_NAME] AS [Column]
    --, [DATA_TYPE] AS [Type]
FROM
    [INFORMATION_SCHEMA].[COLUMNS]
WHERE
    [IS_NULLABLE] = 'NO'
    AND (@Table = '' OR [TABLE_NAME] = @Table)
ORDER BY 
    [TABLE_NAME]

Notes

  • Replace Your table name here on line 1 at the top of the query, with the name of the table you need a list for.

  • If you also need to know the data type of each column, uncomment line 4 by deleting the two dashes at the start of the line.




回答3:


You are able to query from the information _schema all columns that are nullable. Does that get you what you want?

SELECT 
  table_catalog, table_schema, table_name, column_name, is_nullable

  FROM information_schema.columns 
  WHERE table_name = 'users'


来源:https://stackoverflow.com/questions/34096290/how-to-find-the-name-of-not-null-constraints-in-sql-server

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