我想动态地找到表的外键列中存在的NULLs
的数量。
我的情景如下:
我需要编写一个以表名作为参数的存储过程。在给出表名时,如果表有任何外键列,结果应该给我外键列中的NULLs
的数量,否则给出一条消息说“没有外键”。我发现还需要其他输出。我只是无法在外键列中获得NULLs
的编号。
答案 0 :(得分:1)
你可以找到像这样的外键:
SELECT
f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS ReferenceColumnName
FROM
sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
你去吧。你有外键。因此,您可以根据需要更改代码。我希望这会对你有所帮助。
要获取外键约束的名称,请使用:
select distinct name from sys.objects where object_id in
(select fk.constraint_object_id from sys.foreign_key_columns as fk
where fk.referenced_object_id =
(select object_id from sys.tables where name = 'TableOthersForeignKeyInto')
)