mne*_*nic 2 sql-server insert update output-clause
我想在我的应用程序的“SystemSettings”表中添加一条记录,并使用 UPDATE 中的值设置 PK 值。PK 值来自“TS_LASTIDS”表,其中包含此应用程序 (MicroFocus SBM) 中每个表的最大 PK 值。我需要增加该表中的“TS_LASTID”列,并在将新记录插入“SystemSettings”表时使用新值作为 PK。
Insert Into
ts_SystemSettings ( ts_Id, ts_Name, ts_LongValue)
Values (
( -- ******************** This subquery updates the PK in TS_LASTIDS and outputs the new value
Update
ts_LastIds
Set
ts_LastId=ts_LastId+1
Output
INSERTED.ts_LastId
Where
ts_Name = 'SystemSettings'
) , -- ********************
'NSLastChangeId' ,
1 ,
) ;
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚语法。这是 MS SQL Server 2012。
这是使用 OUTPUT...INTO 的示例
--demo setup
drop table if exists InsertTest;
Create Table InsertTest (id int);
drop table if exists UpdateTest;
Create Table UpdateTest (id int);
insert into UpdateTest(id) values(1),(2);
--solution
UPDATE UpdateTest
SET id = id + 1
OUTPUT INSERTED.id
INTO InsertTest;
--verify results of insert
select * from InsertTest
Run Code Online (Sandbox Code Playgroud)
ID
2
3
Run Code Online (Sandbox Code Playgroud)