'禁用'约束阻止MERGE OUTPUT工作

时间:2015-12-14 15:19:07

标签: sql sql-server sql-server-2012

CREATE TABLE a(
    id INT PRIMARY KEY IDENTITY(1,1),
    val INT
);

CREATE TABLE b(
    id INT PRIMARY KEY IDENTITY(1,1),
    val INT
);

CREATE TABLE a_b(
    fk_a INT,
    fk_b INT
);

CREATE TABLE c(
    id INT PRIMARY KEY IDENTITY(1,1),
    a_val INT,
    b_val INT
);

ALTER TABLE a_b ADD CONSTRAINT fk_a_b_fk_a FOREIGN KEY (fk_a) REFERENCES a(id);
ALTER TABLE a_b ADD CONSTRAINT fk_a_b_fk_b FOREIGN KEY (fk_b) REFERENCES b(id);

INSERT INTO a(val) VALUES (1), (2), (3);
INSERT INTO b(val) VALUES (2), (4), (6);


ALTER TABLE a_b NOCHECK CONSTRAINT ALL;

WITH cte AS (
    SELECT
        a.id AS 'a_id',
        a.val AS 'a_val',
        b.id AS 'b_id',
        b.val AS 'b_val'
    FROM a
        INNER JOIN b
            ON a.id = b.id
)
MERGE INTO c
    USING cte ON 1 = 0
WHEN NOT MATCHED THEN
    INSERT (a_val, b_val)
    VALUES (cte.a_val, cte.b_val)
OUTPUT cte.a_id, cte.b_id INTO a_b(fk_a, fk_b);

ALTER TABLE a_b WITH CHECK CHECK CONSTRAINT ALL;

SELECT * FROM c;

我得到的错误是:

  

目标表' a_b' OUTPUT INTO子句不能位于(主键,外键)关系的任何一侧。找到参考约束' fk_a_b_fk_a'。

但是,我非常清楚地禁用了围绕merge语句的约束。有什么方法可以解决这个问题吗?

同样的事情发生在触发器上,并且围绕合并声明禁用它们并不起作用。

1 个答案:

答案 0 :(得分:0)

试试这个

CREATE  TABLE #a(
    id INT PRIMARY KEY IDENTITY(1,1),
    val INT
);

CREATE TABLE #b(
    id INT PRIMARY KEY IDENTITY(1,1),
    val INT
);

CREATE TABLE #a_b(
    fk_a INT,
    fk_b INT
);

CREATE TABLE #c(
    id INT PRIMARY KEY IDENTITY(1,1),
    a_val INT,
    b_val INT
);

ALTER TABLE #a_b ADD CONSTRAINT fk_a_b_fk_a FOREIGN KEY (fk_a) REFERENCES a(id);
ALTER TABLE #a_b ADD CONSTRAINT fk_a_b_fk_b FOREIGN KEY (fk_b) REFERENCES b(id);

INSERT INTO #a(val) VALUES (1), (2), (3);
INSERT INTO #b(val) VALUES (2), (4), (6);


WITH cte AS (

 SELECT
        a.id AS 'a_id',
        a.val AS 'a_val',
        b.id AS 'b_id',
        b.val AS 'b_val'
    FROM #a a
        INNER JOIN #b b
            ON a.id = b.id
)
MERGE INTO #c
    USING cte ON 1 = 0
WHEN NOT MATCHED THEN
    INSERT (a_val, b_val)
    VALUES (cte.a_val, cte.b_val)
OUTPUT cte.a_id, cte.b_id INTO #a_b(fk_a, fk_b);

SELECT * FROM #c;