2011-11-16 96 views
0

我想在當前的SQL INSERT INTO語句中添加查詢。下面是我的表和當前的sql語句。添加檢查重複記錄的額外SQL查詢

我有3個表:

表1用戶名用戶名

表2用戶名狀態

表3用戶名用戶名問題

目前我只有一臺符合以上3個檢查SELECT語句並將結果插入到表3:

INSERT INTO Table3(UserId, Username, Issue) 
SELECT COALESCE(t1.UserId, t2.UserId), t1.UserName 
    , CASE 
     WHEN (t2.userid IS NULL AND t1.userid IS NOT NULL) 
      THEN 'User exists in t1 but not in t2' 
     WHEN (t2.status = 'DELETE' AND t1.userid IS NOT NULL) 
      THEN 'User Exists in t1, but status in t2 is not DELETE' 
     WHEN (t2.userid IS NOT NULL AND t2.status != 'DELETE' AND t1.userid IS NULL) 
      THEN 'Non-Deleted user in t2 does not exist in t1' 
    END 
FROM table1 t1 
FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid 
WHERE (t2.userid IS NULL AND t1.userid IS NOT NULL) 
    OR (t2.status = 'DELETE' AND t1.userid IS NOT NULL) 
    OR (t2.userid IS NOT NULL AND t2.status != 'DELETE' AND t1.userid IS NULL) 

現在我想添加另一個檢查是否檢查重複的用戶標識,並插入用戶標識,用戶名和是起訴'重複用戶名爲''找到表3中找到的任何重複。

  1. 檢查與同蓋相同的用戶ID(如E01和E01不應該存在)
  2. 檢查相同的用戶ID,但不同的瓶蓋(如E01和E01不應該存在)

我應該如何將這個SQL查詢添加到我當前的SQL語句中?

+0

上表3威爾約束阻止你'INSERT'ing第二記錄用同樣的'UserID'加入表格? –

回答

1

如果要插入一個Duplicated userid found記錄(這將在您的Table3導致重複的用戶ID值,可以使用下面的代碼:

INSERT INTO Table3(UserId, Username, Issue) 
SELECT COALESCE(t1.UserId, t2.UserId), t1.UserName 
    , CASE 
     WHEN (t3user.UserId IS NOT NULL OR t3Status.UserId IS NOT NULL) 
      THEN 'Duplicated userid found' 
     WHEN (t2.userid IS NULL AND t1.userid IS NOT NULL) 
      THEN 'User exists in t1 but not in t2' 
     WHEN (t2.status = 'DELETE' AND t1.userid IS NOT NULL) 
      THEN 'User Exists in t1, but status in t2 is DELETE' 
     WHEN (t2.userid IS NOT NULL AND t2.status != 'DELETE' AND t1.userid IS NULL) 
      THEN 'Non-Deleted user in t2 does not exist in t1' 
    END AS Issue 
    FROM table1 t1 
    FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid 
    LEFT JOIN Table3 AS t3user ON t1.UserID = t3user.UserId 
    LEFT JOIN Table3 AS t3status ON t2.UserId = t3status.UserId 
    WHERE 
    (
     (t2.userid IS NULL AND t1.userid IS NOT NULL) 
     OR (t2.status = 'DELETE' AND t1.userid IS NOT NULL) 
     OR (t2.userid IS NOT NULL AND t2.status != 'DELETE' AND t1.userid IS NULL) 
    )