为什么这个T-SQL重复结果

时间:2016-10-17 10:49:03

标签: sql sql-server tsql

为什么这个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

2 个答案:

答案 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 

现在每个tabledistinct依赖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;