我试图在SQL服务器中使用if
语句进行插入,但仍然对此感到困惑。
SELECT A.id, B.id
FROM table_a A
LEFT JOIN table_b B ON A.id_a = B.id_b
会是这样
a.id b.id
--------------------
1 1
2 null
如何从table_a
插入table_b
(a.id = 1
)中不为null的方法到table_insert_1
,以及如果null
(a.id = 2
)插入table_a
至table_insert_2
吗?
答案 0 :(得分:0)
您可以将其简化为:
INSERT INTO table_insert_1 (COL1, . . . )
SELECT A.Col1, . . .
FROM table_a A
WHERE EXISTS (SELECT 1 FROM table_b B WHERE B.id_b = A.id_a);
INSERT INTO table_insert_2 (COL1, . . . )
SELECT A.Col1, . . .
FROM table_a A
WHERE NOT EXISTS (SELECT 1 FROM table_b B WHERE B.id_b = A.id_a);
答案 1 :(得分:0)
您需要两个稍微不同的INSERT
命令:
INSERT INTO table_insert_1
SELECT A.id, B.id
FROM table_a A
INNER JOIN table_b B ON A.id_a = B.id_b
WHERE A.id = 1;
INSERT INTO table_insert_2
SELECT A.id, B.id
FROM table_a A
LEFT JOIN table_b B ON A.id_a = B.id_b
WHERE B.id IS NULL A.id = 1;
第一个UPDATE
使用INNER JOIN
仅选择可以在第二个表中找到的记录。第二个使用LEFT JOIN
(可选),并带有WHERE
子句来过滤匹配的记录。
答案 2 :(得分:0)
您可以通过以下代码编写if else
案例。
IF ISNULL(@Id, 0)
BEGIN
"your sql statement"
END
else
BEGIN
"your sql statement"
END