不要重复自己:相同的SQL查询,但两个不同的表

我有一个SQL查询具有完全相同的代码,但有两个不同的表(AUDIT_TRAIL_ARCHIVE和AUDIT_TRAIL).我使用“UNION ALL”来获得一个结果.

优秀的程序员使用“Don’t repeat yourself”原则.优秀的程序员避免WET(写两次).

如何用“不要重复自己”的原则重写这段代码?

SELECT REPLACE (ENTITY_KEY, 'rss_user_name=CN=', '')
 FROM    AUDIT_TRAIL_ARCHIVE AU
   INNER JOIN
      (SELECT RSS_USER_NAME
         FROM RSS_USER
        WHERE RSS_NAME = 'rmad'
              AND ADD_INFO_MASTER LIKE '%__47__UPN=%@richemont.com%') FALSCH
   ON REPLACE (AU.ENTITY_KEY, 'rss_user_name=CN=', '') =
         FALSCH.RSS_USER_NAME
WHERE     AU.RSS_NAME = 'rmad'
   AND AU.TABLE_NAME = 'rss_user'
   AND AU.ACTION = 'Insert'
   AND AU.ENTITY_KEY LIKE 'rss_user_name=CN=%'
   AND AU.ORIGIN != 'RSS'
UNION ALL
SELECT REPLACE (ENTITY_KEY, 'rss_user_name=CN=', '')
 FROM    AUDIT_TRAIL AU
   INNER JOIN
      (SELECT RSS_USER_NAME
         FROM RSS_USER
        WHERE RSS_NAME = 'rmad'
              AND ADD_INFO_MASTER LIKE '%__47__UPN=%@richemont.com%') FALSCH
   ON REPLACE (AU.ENTITY_KEY, 'rss_user_name=CN=', '') =
         FALSCH.RSS_USER_NAME
WHERE     AU.RSS_NAME = 'rmad'
   AND AU.TABLE_NAME = 'rss_user'
   AND AU.ACTION = 'Insert'
   AND AU.ENTITY_KEY LIKE 'rss_user_name=CN=%'
   AND AU.ORIGIN != 'RSS'
最佳答案
例如:

SELECT REPLACE (ENTITY_KEY, 'rss_user_name=CN=', '')
 FROM    (select * --or relevant columns
          from AUDIT_TRAIL_ARCHIVE AU
          union all
          select * 
          from AUDIT_TRAIL AU
           ) AU
   INNER JOIN
      (SELECT RSS_USER_NAME
         FROM RSS_USER
        WHERE RSS_NAME = 'rmad'
              AND ADD_INFO_MASTER LIKE '%__47__UPN=%@richemont.com%') FALSCH
   ON REPLACE (AU.ENTITY_KEY, 'rss_user_name=CN=', '') =
         FALSCH.RSS_USER_NAME
WHERE     AU.RSS_NAME = 'rmad'
   AND AU.TABLE_NAME = 'rss_user'
   AND AU.ACTION = 'Insert'
   AND AU.ENTITY_KEY LIKE 'rss_user_name=CN=%'
   AND AU.ORIGIN != 'RSS'

转载注明原文:不要重复自己:相同的SQL查询,但两个不同的表 - 代码日志