检查哪一列不可为空

时间:2018-11-09 13:57:39

标签: sql-server tsql

我想知道是否有一个脚本可以运行,以查看哪些列不可为空而不是整个数据库上的标识列?

我用Google搜索结果,但发现的唯一结果就是检查哪些数据为空的答案。

2 个答案:

答案 0 :(得分:2)

您可以这样做

USE YourDatabase
GO

SELECT T.name TableName,
       C.name ColumnName
FROM Sys.Tables T INNER JOIN Sys.Columns C ON T.object_id = C.object_id
WHERE C.is_nullable = 0
      AND
      C.is_identity = 0;

或者这个

SELECT T.Name TableName,
       STUFF(
              (
                SELECT ',' + C.Name
                FROM Sys.Columns C
                WHERE C.object_id = T.object_id
                      AND
                      C.is_nullable = 0
                      AND
                      C.is_identity = 0
                FOR XML PATH('')
              ), 1, 1, ''
       ) HasThosNonNullableColumns
FROM Sys.Tables T;

Demo

答案 1 :(得分:1)

所以我想到了查看sysobjectssys.columns视图,并因此加入了表:

select
    o.name  [Table]
    ,c.name [Column]
from
      sys.columns c
inner join 
       sysobjects o on
       c.object_id = o.id
where
      c.is_nullable = 0
      and c.is_identity = 0
order by 
      o.name
      ,c.name

这很有帮助。