我正在尝试从select语句执行批量插入,但有时我想将Identity2从Table2保存到Table1,但有时我希望Table2中没有数据时自动生成表中的Identity那么如何实现呢?
INSERT INTO Table (ID,Name)
SELECT
CASE WHEN Col1 IS NOT NULL THEN Col1 ELSE @@identity END ID,
Col2 Name,
FROM Table2
这是可能的还是我必须进行2个单独的批量导入过程?
答案 0 :(得分:1)
是的,您需要两个批量插入:
SET IDENTITY_INSERT Table ON
INSERT INTO Table (ID,Name)
SELECT
Col1
Col2 Name
FROM Table2
WHERE Col1 IS NOT NULL
SET IDENTITY_INSERT Table OFF
INSERT INTO Table (Name)
SELECT
Col2 Name
FROM Table2
WHERE Col1 IS NULL