2014-02-25 79 views
0

我有一個查詢返回ID,ORG IDNAME遍歷臨時表並插入到另一個表中

代碼:

CREATE TABLE #TMP (ORG_ID INT) 

INSERT INTO #TMP SELECT ORG_ID FROM [dbo].[fx_Rights_OrgIDs] (331) 

SELECT [BRN_ID],[BRN_ORGID],[BRN_Name] 
FROM [dbo].[BranchDetails] 
WHERE [BRN_ORGID] IN (SELECT ORG_ID FROM #TMP) 

DROP TABLE #TMP 

返回:

BRA_ID BRA_ORGID  BRA_Name 

289  333   Office 

290  334   Store 

我想要做的是通過迭代和#TMP插入到另一個表:SitePrefix如果SitePrefix存在不插入值。

因此,例如插入BRA_Nametemp tableSitePrefix,如果它存在,則跳過。

SitePrefix列如下:(SPF_IDSPF_NameSPF_Prefix

SPF_ID是自動生成的,SPF_Name應該來自BRA_Name和SPF_PrefixEMS

回答

0

嘗試它採用EXCEPT被設置在下方查詢SQL Server中的差異運算符

INSERT INTO SitePrefix 
    SELECT [BRN_Name], 'EMS' 
    FROM [dbo].[BranchDetails] 
    WHERE [BRN_ORGID] IN (SELECT ORG_ID FROM #TMP) 
    EXCEPT 
    SELECT SPF_Name, 'EMS' 
    FROM SitePrefix 
0

試試這個,然後告訴任何問題,

MERGE siteprefix AS T 
using (SELECT [brn_id], 
       [brn_orgid], 
       [brn_name] 
     FROM [dbo].[branchdetails] 
     WHERE [brn_orgid] IN (SELECT org_id 
           FROM [dbo].[Fx_rights_orgids] (331))) AS s 
ON t.spf_name = brn_name 
WHEN NOT matched THEN 
    INSERT (spf_name, 
      spf_prefix) 
    VALUES (brn_name, 
      brn_orgid) 
相關問題