Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't repeat yourself: same SQL query, but two different tables

I have an SQL query with exact the same code, but two different tables (AUDIT_TRAIL_ARCHIVE and AUDIT_TRAIL). I use "UNION ALL" to have one result.

Good programmers use "Don't repeat yourself" principle. Good programmers avoid WET (write everything twice).

Howto rewrite this code with "Don't repeat yourself" principle?

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'
like image 660
Josefine Avatar asked Apr 12 '13 12:04

Josefine


1 Answers

For example:

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'
like image 191
Florin stands with Ukraine Avatar answered Oct 05 '22 07:10

Florin stands with Ukraine