我已经'继承了'这是一个很棒的TSQL代码:
显然这很糟糕(性能和优雅的原因)!!
问题 起初,这看起来像MERGE使用的标准情况。我试过了:
MERGE [dbo].[TableA] AS Target
USING <cursor data set as a select statement> as Src on target.IDA = Src.IDA
WHEN MATCHED
//update
WHEN NOT MATCHED
//insert <------ Fails because obviously a new IDB is required
还尝试了各种方法,例如nested select that sends IDB on the OUTPUT
,但它失败了,因为IDB是PK。
其他类型的合并也失败了,例如:
MERGE Table A with <cursor data set as a select statement>
...
MERGE Table A with Table B
WHEN NOT MATCHED
//insert on Table A
WHEN NOT MATCHED
// Update Table B
有人对此有所了解吗?基本上我认为如果我们推广这个问题将是:
Can I insert and return the PK in one statement that can be nested in other statements
提前感谢您的回复
乔治
答案 0 :(得分:3)
如果您在表上有自动生成的PK,则可以使用与此类似的代码。否则,只需将INSERT更改为TableA即可从表中获取PK。
DECLARE @OldData CHAR(10)
SET @OldData = 'Old'
DECLARE @NewData CHAR(10)
SET @NewData = 'New'
CREATE TABLE #TableA
(
IDA INT IDENTITY(1,1) PRIMARY KEY,
IDB INT NOT NULL,
DataA CHAR(10)
)
CREATE TABLE #TableB
(
IDB INT IDENTITY(1,1) PRIMARY KEY,
DataB CHAR(10)
)
DECLARE @IDsToUpsert TABLE
(
ID INT
)
-- Add test values for existing rows
INSERT INTO #TableB
OUTPUT INSERTED.IDB, @OldData
INTO #TableA
SELECT @OldData UNION ALL
SELECT @OldData UNION ALL
SELECT @OldData UNION ALL
SELECT @OldData
-- Add test values for the rows to upsert
INSERT INTO @IDsToUpsert
SELECT 1 UNION -- exists
SELECT 3 UNION -- exists
SELECT 5 UNION -- does not exist
SELECT 7 UNION -- does not exist
SELECT 9 -- does not exist
-- Data Before
SELECT * From #TableA
SELECT * From #TableB
DECLARE rows_to_update CURSOR
FOR SELECT ID FROM @IDsToUpsert
DECLARE @rowToUpdate INT
DECLARE @existingIDB INT
OPEN rows_to_update;
FETCH NEXT FROM rows_to_update
INTO @rowToUpdate;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRANSACTION
IF NOT EXISTS
(
SELECT 1 FROM #TableA WITH (UPDLOCK, ROWLOCK, HOLDLOCK)
WHERE IDA = @rowToUpdate
)
BEGIN
-- Insert into B, then insert new val into A
INSERT INTO #TableB
OUTPUT INSERTED.IDB, INSERTED.DataB
INTO #TableA
SELECT @NewData
-- Change code here if PK on TableB is not autogenerated
END
ELSE
BEGIN
-- Update
UPDATE #TableA
SET DataA = @NewData
WHERE IDA = @rowToUpdate
END
COMMIT TRANSACTION
FETCH NEXT FROM rows_to_update
INTO @rowToUpdate;
END
CLOSE rows_to_update;
DEALLOCATE rows_to_update;
SELECT * FROM #TableA
SELECT * FROM #TableB
DROP TABLE #TableA
DROP TABLE #TableB
答案 1 :(得分:1)
回答你的一般问题 - '我可以在一个可以嵌套在其他语句中的语句中插入和返回PK' - 是的,绝对的。但这取决于你创建PK的逻辑。在这种情况下,似乎要生成PK,您需要插入到不同的表中,然后从那里获取新生成的ID。这不是非常有效(恕我直言),除非有这样做的非常具体的原因。自动增量,GUID等倾向于更好地作为PK。如果你可以简化/改变它背后的逻辑,你可以找到一种更简单的方法来实现它,所以PK'CAN'可以在一个语句/函数中生成,因此可以在其他语句中使用。