2016-01-11 69 views
1

我們需要創建一個script這將insert只有新近createdofficesdistricts納入Data table。我們需要檢查OfficeDistricttables新的Records,如果數據存在,我們需要insert他們。如何在sql服務器中使用帶有OR子句的IF EXISTS語句

我們已經嘗試了下面的語法爲此,

IF EXISTS (
    SELECT 1 
    FROM [dbo].[office] o 
    LEFT OUTER JOIN [dbo].[Datatable] a ON (o.OfficeID = a.OfficeID) 
    WHERE a.OfficeID IS NULL 
) 
OR (
IF EXISTS (
    SELECT 1 
    FROM [dbo].[District] o 
    LEFT OUTER JOIN [dbo].[Datatable] a ON (o.DistrictID = DistrictID) 
    WHERE a.DistrictID IS NULL 
) 
) 
BEGIN 
    -- //CODE 
END 

但SSMS給syntax error這一點。如何實現上述場景?

回答

6

應該... OR EXISTS(而不是OR (if EXISTS(

IF EXISTS 
(
    SELECT 1 
    FROM [dbo].[office] o 
    LEFT OUTER JOIN [dbo].[Datatable] a 
     ON (o.OfficeID = a.OfficeID) 
    WHERE a.OfficeID IS NULL 
) 
OR EXISTS 
(
    SELECT 1 
    FROM [dbo].[District] o 
    LEFT OUTER JOIN [dbo].[Datatable] a 
     ON (o.DistrictID = DistrictID) 
    WHERE a.DistrictID IS NULL 
) 
BEGIN 
    //CODE 
END