【发布时间】:2016-03-22 19:58:48
【问题描述】:
出于审计目的,我使用触发器将更改插入到审计表中。然后我使用 CTE 递归地获取特定项目的所有审计行。
这个SQLFiddle 添加了一些审计行和我当前正在使用的 CTE。
这是 CTE:
;WITH cteAudit AS
(
SELECT id, [user_name], date_time, item_parent_type, item_parent_id,
item_type, item_id, item_action, row_guid, 1 AS audit_level
FROM audit
WHERE
(item_type = 22 AND item_id = 925)
UNION ALL
SELECT a.id, a.[user_name], a.date_time, a.item_parent_type, a.item_parent_id,
a.item_type, a.item_id, a.item_action, a.row_guid, cteAudit.audit_level + 1
FROM audit a
INNER JOIN cteAudit
ON a.item_parent_id = cteAudit.item_id
AND a.item_parent_type = cteAudit.item_type
WHERE
a.item_parent_type <> a.item_type AND
a.item_parent_id <> a.item_id
)
SELECT
cteAudit.id,
cteAudit.[user_name],
cteAudit.date_time,
cteAudit.item_parent_id,
@itemtype AS item_type,
cteAudit.item_id,
item_action,
cteAudit.audit_level,
CONVERT(nvarchar(36), cteAudit.row_guid) AS row_guid
ORDER BY date_time DESC, audit_level desc
但是,对于这个 CTE,我有 2 个问题:
- 查询未返回所有 13 行。它不显示第 11-13 行。这是因为主表(客户)没有经过审核,因为用户只是更改了联系人的地址。
发生这种情况是因为我修改了第 3 级(联系人),并且此级别有一个到第 2 级(联系人列表)的链接。但是第 2 级,它有到第 1 级(客户)的链接,没有被修改,并且因此不在审计表中,因此没有到第一级的链接。
- 查询返回重复记录。
如何返回主表的所有行?为什么查询返回重复的行?
【问题讨论】:
标签: sql sql-server common-table-expression