通过此查询,我获得了所有数据库CHECK
,FOREIGN_KEY
,PRIMARY_KEY
和UNIQUE_KEY
约束的列表。
SELECT
o.object_id as ID, o.name AS Name,
OBJECT_NAME(o.parent_object_id) AS TableName,
o.type_desc AS TypeName,
cs.COLUMN_NAME as ColumnName
FROM
sys.objects o
LEFT JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cs ON o.name = cs.CONSTRAINT_NAME
WHERE
o.type = 'C' or o.type = 'F' or o.type = 'PK' or o.type = 'UQ'
然而,其中有一些有很多'ColumnName',我想结束这个。
例如:
'PK_ENTITE_SIGN_DOSSIER_ID_DOSSIER_ID_ENTITE_ID_GROUPE_SIGN_ID_PERSONNE_ID_SCHEMA'
是表PRIMARY_KEY
上的ENTITE_SIGN_DOSSIER
,其中包含ID_DOSSIER
,ID_ENTITE
,ID_GROUPE_SIGN
,ID_PERSONNE
和ID_SCHEMA
(5)在这种情况下,我的查询为此约束返回5行。
如何在查询结果上连接这些列名?
非常感谢你的帮助
答案 0 :(得分:3)
这是标准xml
和stuff
功能技巧:
SELECT o.object_id AS ID ,
o.name AS Name ,
OBJECT_NAME(o.parent_object_id) AS TableName ,
o.type_desc AS TypeName ,
ca.ColumnName
FROM sys.objects o
CROSS APPLY ( SELECT STUFF(( SELECT ', ' + cs.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cs
WHERE o.name = cs.CONSTRAINT_NAME
FOR
XML PATH('')
), 1, 2, '') AS ColumnName
) ca
WHERE o.type = 'C'
OR o.type = 'F'
OR o.type = 'PK'
OR o.type = 'UQ'
ORDER BY ID