假設table3
生成順序整數值,像IDENTITY
屬性具有值1的增量,可以生成那些自己使用ROW_NUMBER()
,然後INSERT
荷蘭國際集團生成的值成table3
。
但是,由於您自己生成了值,因此您必須鎖定table3
以防止語句運行時發生更改。
讓我們設置一個測試用例。
USE tempdb
GO
IF OBJECT_ID('table1', 'U') IS NOT NULL DROP TABLE table1;
IF OBJECT_ID('table2', 'U') IS NOT NULL DROP TABLE table2;
IF OBJECT_ID('table3', 'U') IS NOT NULL DROP TABLE table3;
CREATE TABLE table1 (
field1 int,
field2 int,
field3 int,
field4 int,
field5 int
);
CREATE TABLE table2 (
field1_from_table2 int,
field2_from_table2 int
);
CREATE TABLE table3 (
field1_from_table3 int IDENTITY(1,1)
);
INSERT INTO table2
VALUES (1000, 2000)
, (1001, NULL);
GO
-- INSERT 20 records to generate some IDENTITY increments.
INSERT INTO table3 DEFAULT VALUES
GO 20
下面是生成順序值的示例代碼。
BEGIN TRANSACTION;
SET IDENTITY_INSERT table3 ON;
GO
DECLARE @someID1 int = 100
, @someID2 int = 200;
DECLARE @output table (field4 int, field5 int);
-- Lock table3 exclusively to prevent INSERTs that spoil IDENTITY values.
SELECT TOP(0) 1 FROM table3 WITH (HOLDLOCK, TABLOCKX);
-- INSERT into table1, generating sequential integers
-- and saving the output in @output.
INSERT INTO table1
OUTPUT inserted.field4
, inserted.field5
INTO @output(field4, field5)
SELECT @someID1
, field1_from_table2
, @someID2
, field2_from_table2
, CASE
WHEN field2_from_table2 IS NOT NULL THEN field2_from_table2
ELSE (ROW_NUMBER() OVER (PARTITION BY field2_from_table2
ORDER BY field2_from_table2))
+ (SELECT MAX(field1_from_table3) FROM table3)
END
FROM table2;
-- INSERT generated integer values.
INSERT INTO table3 (field1_from_table3)
SELECT field5
FROM @output
WHERE field4 IS NULL;
SET IDENTITY_INSERT table3 OFF;
GO
COMMIT;
SELECT * FROM table1;
SELECT * FROM table2;
SELECT * FROM table3;
你不能讓你的發言'CASE'裏面 - 它只是設計用來**返回值**('WHEN .... THEN(這裏的一些值)') –
@Chorinator,如果'field3_from_table2'是'NULL',是在你的例子中'INSERT'到table1的行嗎? – gonsalu
@Gonsalu不,不在示例中,但它是一個非常簡單的表格。它只包含一列,它是一個身份。我僅將該表用作Id調度程序。 – Chorinator