插入..选择..案例 - 有没有办法获得2列?

时间:2015-03-05 10:30:10

标签: tsql insert case

a有一张桌子,我想在这张桌子上插入一些东西(非常原始的我; P)。

所以我有:

INSERT into TARGET_TABLE ([...], tcol1, tcol2)
SELECT [...],
        (SELECT
            CASE
                WHEN smth IS NOT NULL THEN SELECT Q_COL1 [...]
                WHEN smthelse IS NOT NULL THEN SELECT Q_COL1 [from the same table but via different fk and through another tables]
        END)
FROM another_table

它工作正常。

BUT

我需要来自另一个严格连接到Q_COL1的表的另一个值,并且可以使用SELECT Q_COL1部分中的一个简单JOIN轻松获得。

但是(SELECT CASE ...)应该只返回一个值。

Ofc我可以做另一轮,只是添加另一个插入但我不喜欢它 - 我宁愿这样做一次,插入一次。

任何线索? :)

编辑: 我想通了!

INSERT INTO TARGET_TABLE([...], tcol1, tcol2)
SELECT .... COALESCE(t1c1.val1, t2c1.val1), COALESCE(t1c2.val2, t2c2.val2)
FROM another_table
JOIN table_in_between1..
JOIN table_in_between2..
JOIN table_for_col1 t1c1 ON t1c1.Id=table_in_between1.idt1c1
JOIN table_for_col1 t2c1 ON t2c1.Id=table_in_between2.idt2c1
JOIN table_for_col2 t1c2 ON t1c2.Id = t1c1.id..
JOIN table_for_col2 t2c2 ON t2c2.Id = t2c1.Id...

此外,执行计划现在要好得多(没有流聚合和急切的假脱机)。

1 个答案:

答案 0 :(得分:1)

INSERT INTO TARGET_TABLE([...], tcol1, tcol2)
SELECT .... COALESCE(t1c1.val1, t2c1.val1), COALESCE(t1c2.val2, t2c2.val2)
FROM another_table
JOIN table_in_between1..
JOIN table_in_between2..
JOIN table_for_col1 t1c1 ON t1c1.Id=table_in_between1.idt1c1
JOIN table_for_col1 t2c1 ON t2c1.Id=table_in_between2.idt2c1
JOIN table_for_col2 t1c2 ON t1c2.Id = t1c1.id..
JOIN table_for_col2 t2c2 ON t2c2.Id = t2c1.Id...

此外,执行计划现在要好得多(没有流聚合和急切的假脱机)。