SQL Server-使用VIEW更新多个基本表

时间:2019-01-17 23:08:21

标签: sql sql-server tsql

我有一个“基本”表,我希望通过“自定义”字段进行扩展-但我不想更改基本表的完整性(只需向其添加自定义列)。这是表的定义:

$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -s - -e .
{
  "foo": "lorem",
  "bar": "ipsum"
}

要获得所有相关数据的单一视图,我创建了一个视图:

CREATE TABLE CHRIS_BASE (
    ID      UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID(),
    B1      VARCHAR(20),
    B2      VARCHAR(20)
    PRIMARY KEY(ID)
)


CREATE TABLE CHRIS_CUSTOM (
    ID          UNIQUEIDENTIFIER NOT NULL FOREIGN KEY REFERENCES dbo.CHRIS_BASE(ID) ON DELETE CASCADE,
    C1          VARCHAR(20),
    C2          VARCHAR(20)
    PRIMARY KEY (ID) 
)

我将如何创建“ INSTEAD OF”触发器来处理此问题?最重要的是,显然,当我执行插入操作时,键是匹配的。我尝试过:

CREATE VIEW CHRIS_VW AS
    SELECT cb.ID, cb.B1, cb.B2, cc.C1, cc.C2
    FROM dbo.CHRIS_BASE AS cb
    LEFT OUTER JOIN dbo.CHRIS_CUSTOM AS cc ON cc.ID = cb.ID

但是我显然遇到了错误-因为我无法将生成的ID从“基本”表携带到“自定义”表。

CREATE TRIGGER CHRIS_VW_TR_INSERT ON CHRIS_VW
INSTEAD OF INSERT
AS
BEGIN

    INSERT INTO dbo.CHRIS_BASE (B1, B2)
    SELECT B1, B2
    FROM INSERTED

    INSERT INTO dbo.CHRIS_CUSTOM (C1, C2)
    SELECT C1, C2
    FROM INSERTED

END

收益:

INSERT INTO CHRIS_VW
    (B1, B2, C1, C2)
VALUES
    ('R1-F1-BASE','R1-F2-BASE','R1-F1-CUSTOM','R1-F2-CUSTOM'),
    ('R2-F1-BASE','R2-F2-BASE','R2-F1-CUSTOM','R2-F2-CUSTOM'),
    ('R3-F1-BASE','R3-F2-BASE','R3-F1-CUSTOM','R3-F2-CUSTOM'),
    ('R4-F1-BASE','R4-F2-BASE','R4-F1-CUSTOM','R4-F2-CUSTOM')

还要在UPDATE和DELETE触发器上寻找方向。

1 个答案:

答案 0 :(得分:3)

使用.us子句,但是它变得很复杂。如果我们假设<?php require('fpdf181/fpdf.php'); function pdfBuild($count) { $pdf = new FPDF(); $pdf->AliasNbPages(); $pdf->SetFont('Times','',12); for($a=0;$a<$count;$a++) { $pdf->AddPage(); //Add stuff to PDF } return $pdf; } $filenamea = "testa.pdf"; $filenameb = "testb.pdf"; $pdfa = pdfBuild(2); $pdfa->Output('D', $filenamea); $pdfb = pdfBuild(5); $pdfb->Output('D', $filenameb); echo 'Done'; ?> / OUTPUT在加载数据时是唯一的:

B1