为什么这个T-SQL重复结果?
此查询相当通用,因此应在任何数据库中复制ok。
我在TextLine列中复制了USP ...
SELECT DISTINCT b.name as TableName,
STUFF((
SELECT ', ' + OBJECT_NAME(a.object_id)
FROM sys.sql_dependencies a
WHERE a.referenced_major_id = b.object_id
ORDER BY 1
For XML PATH ('')
), 1, 1, '') AS [TextLine]
FROM sys.sql_dependencies a JOIN sys.tables b ON a.referenced_major_id = b.object_id
ORDER BY 1 ASC
答案 0 :(得分:4)
将DISTINCT
添加到子查询
SELECT DISTINCT b.name AS TableName,
Stuff((SELECT DISTINCT ', ' + Object_name(a.object_id) --Here
FROM sys.sql_dependencies a
WHERE a.referenced_major_id = b.object_id
ORDER BY 1
FOR XML PATH ('')), 1, 1, '') AS [TextLine]
FROM sys.sql_dependencies a
JOIN sys.tables b
ON a.referenced_major_id = b.object_id
ORDER BY TableName ASC
现在每个table
仅distinct
依赖objects
将被连接
答案 1 :(得分:1)
您的查询过于复杂。您不需要外部查询中的join
,也可能不需要select distinct
:
SELECT t.name as TableName,
Stuff((SELECT DISTINCT ', ' + Object_name(d.object_id) --Here
FROM sys.sql_dependencies d
WHERE d.referenced_major_id = t.object_id
ORDER BY 1
FOR XML PATH ('')
), 1, 1, '') AS [TextLine]
FROM sys.tables t
ORDER BY TableName ASC;
实际上,删除外部JOIN
可能也会删除内部查询中的重复项:
SELECT t.name as TableName,
Stuff((SELECT ', ' + Object_name(d.object_id) --Here
FROM sys.sql_dependencies d
WHERE d.referenced_major_id = t.object_id
ORDER BY 1
FOR XML PATH ('')
), 1, 1, '') AS [TextLine]
FROM sys.tables t
ORDER BY TableName ASC;