我的 SQL 视图查询有一些问题。我有几个重复的查询,我认为它不应该是这样的。这只是更大的一部分:
WITH auditlogs ([AuditLogId], [OperationCode], [Operation], [Table], [RowId], [Timestamp], [UserUid], [UserName], [IpAddress], [OperationSet], [ContextUid], [Field], [OldValue], [NewValue]) AS
(
SELECT
al.[Id] AS [AuditLogId],
al.[Operation] as [OperationCode],
CASE al.[Operation]
WHEN 0 THEN 'New'
WHEN 1 THEN 'Update'
WHEN 2 THEN 'Delete'
ELSE 'Warning'
END AS [Operation],
al.[EntityName] AS [Table],
CASE al.[EntityId]
WHEN -1 THEN NULL
ELSE al.[EntityId]
END AS [RowId],
al.[Timestamp],
al.[UserUid],
al.[UserName],
al.[IpAddress],
al.[OperationSet],
al.[ContextUid],
alf.[Name],
alf.[OldValue],
alf.[NewValue]
FROM [AuditLog] AS al
INNER JOIN [AuditLogField] AS alf ON alf.AuditLogId = al.Id
)
SELECT [AuditLogId], --- ATTACHUSERS
[OperationCode], [Operation], [Table], [RowId], [Timestamp], alx.[UserUid], [UserName],
[IpAddress], [OperationSet], [ContextUid], 'User' AS [Field], null, u.[FirstName] + ' ' + u.[LastName], s.Id
FROM (
SELECT [AuditLogId],
[OperationCode], [Operation], [Table], [RowId], [Timestamp], [UserUid], [UserName],
[IpAddress], [OperationSet], [ContextUid],
MAX(case when [Field] = 'UserUid' then [NewValue] end) AS AddedUserUid,
MAX(case when [Field] = 'TenantId' then [NewValue] end) TenantId
FROM [auditlogs] AS al
WHERE al.[Table] = 'TenantUser' AND OperationCode = 0
GROUP BY [AuditLogId], [OperationCode], [Operation], [Table], [RowId], [Timestamp], al.[UserUid], [UserName],
[IpAddress], [OperationSet], [ContextUid]
) AS alx
INNER JOIN [User] AS u ON u.[Uid] = CAST(alx.AddedUserUid AS uniqueidentifier)
INNER JOIN [Tenant] AS t ON alx.TenantId = t.Id
INNER JOIN [Subscription] AS s ON s.TenantId = t.id
UNION ALL
SELECT al.[AuditLogId], --- DETTACHUSERS
al.[OperationCode], al.[Operation], al.[Table], al.[RowId], al.[Timestamp], al.[UserUid], al.[UserName],
al.[IpAddress], al.[OperationSet], al.[ContextUid], 'User' AS [Field], null, u.[FirstName] + ' ' + u.[LastName], s.Id
FROM [auditlogs] AS al
INNER JOIN (
SELECT TOP 1 *
FROM (
SELECT [AuditLogId],
[OperationCode], [Operation], [Table], [RowId], [Timestamp], [UserUid], [UserName],
[IpAddress], [OperationSet], [ContextUid],
MAX(case when [Field] = 'UserUid' then [NewValue] end) AS AddedUserUid,
MAX(case when [Field] = 'TenantId' then [NewValue] end) TenantId
FROM [auditlogs] AS al
WHERE al.[Table] = 'TenantUser' AND OperationCode = 0
GROUP BY [AuditLogId], [OperationCode], [Operation], [Table], [RowId], [Timestamp], al.[UserUid], [UserName],
[IpAddress], [OperationSet], [ContextUid]
) AS added
ORDER BY [Timestamp] DESC
) AS alx ON alx.RowId = al.RowId AND al.OperationCode = 2
INNER JOIN [User] AS u ON u.[Uid] = CAST(alx.AddedUserUid AS uniqueidentifier)
INNER JOIN [Tenant] AS t ON alx.TenantId = t.Id
INNER JOIN [Subscription] AS s ON s.TenantId = t.id
我知道我的视图可以由其他人组成,我的意思是,将其拆分为几个较小的视图,以便重用它们并避免重复的部分。但是我想知道这是否是一种好方法,或者是否有另一种更好的方法。
拆分它,这是最好的解决方案吗?