在SQL Server(SSMS)中替代左外部联接

时间:2018-07-01 16:37:55

标签: sql-server substitution

当我尝试在下面的VIEW中创建唯一索引时,出现以下错误,

  

信息10113,第16级,状态1,第431行
  无法在视图“ V3CONv.ADVANCED.BillsToBeDeletedVIEW”上创建索引,因为它使用LEFT,RIGHT或FULL OUTER联接,并且索引视图中不允许使用OUTER联接。考虑改用INNER联接。

INNER JOIN将产生与所需数据集不同的数据集,我该如何替换Microsoft SQL Server中的LEFT OUTER JOIN?

CREATE VIEW ADVANCED.BillsToBeDeletedVIEW
WITH SCHEMABINDING
AS
    SELECT DISTINCT 
        I_BILLNUMBER 
    FROM 
        ADVANCED.BIF951_C 
    LEFT OUTER JOIN 
        ADVANCED.BIF003ToBeDeleted ON BIF003ToBeDeleted.C_CUSTOMER = ADVANCED.BIF951_C.C_CUSTOMER 
                                   AND BIF003ToBeDeleted.C_ACCOUNT = ADVANCED.BIF951_C.C_ACCOUNT
    WHERE 
        BIF003ToBeDeleted.C_CUSTOMER IS NOT NULL
        OR D_BILLDATE < '2016-06-01' 

1 个答案:

答案 0 :(得分:1)

您可以使用两个单独的索引视图,如下所示:

create schema ADVANCED
go

    create table ADVANCED.BIF951_C(id int, I_BILLNUMBER int, D_BILLDATE datetime, C_CUSTOMER INT, C_ACCOUNT INT)

    CREATE TABLE ADVANCED.BIF003ToBeDeleted(ID INT, C_CUSTOMER INT, C_ACCOUNT INT)

    GO

    CREATE OR ALTER VIEW ADVANCED.BillsToBeDeletedVIEW_1
    WITH SCHEMABINDING
    AS
        SELECT  
            I_BILLNUMBER 
        FROM 
            ADVANCED.BIF951_C 
        JOIN 
            ADVANCED.BIF003ToBeDeleted ON BIF003ToBeDeleted.C_CUSTOMER = ADVANCED.BIF951_C.C_CUSTOMER 
                                       AND BIF003ToBeDeleted.C_ACCOUNT = ADVANCED.BIF951_C.C_ACCOUNT
     GO

     CREATE UNIQUE CLUSTERED INDEX IX_BillsToBeDeletedVIEW_1 ON ADVANCED.BillsToBeDeletedVIEW_1(I_BILLNUMBER)
     GO


    CREATE OR ALTER VIEW ADVANCED.BillsToBeDeletedVIEW_2
    WITH SCHEMABINDING
    AS


        SELECT I_BILLNUMBER
        FROM  ADVANCED.BIF951_C 
        WHERE D_BILLDATE < CONVERT(DATETIME,'2016-06-01',120)

        GO


     CREATE UNIQUE CLUSTERED INDEX IX_BillsToBeDeletedVIEW_2 ON ADVANCED.BillsToBeDeletedVIEW_2(I_BILLNUMBER)
     GO

     CREATE OR ALTER VIEW ADVANCED.BillsToBeDeletedVIEW
     AS 

       SELECT I_BILLNUMBER
       FROM BillsToBeDeletedVIEW_1
       UNION
       SELECT I_BILLNUMBER
       FROM BillsToBeDeletedVIEW_2