简体   繁体   中英

SQL: Update and Insert with condition

I would like to know if this is possible. I would like to update a record only if the typeId equal my value and add a record in table B if that's the case.

TableA:

id (PK, int)  
typeId (int)

TableB:

id (PK, int)  
tableAId (FK, int)
note (nvarchar)

My SQL script:

UPDATE [dbo].[TableA] 
   SET [TypeId] = CASE 
     WHEN [TypeId] = 4 THEN 6 AND
        (INSERT INTO [dbo].[TableB] ([tableAId],[note])
         VALUES ([dbo].[TableA].Id,'type has changed'))
     ELSE [Id]
END

The script above looks like I want to achieve but obviously it's incorrect. How can I do multiple things in my case condition? Update a value and insert a record with the current id?

Data sample:

Table A (id, typeId)
1, 4
2, 5
3, 2

Table B (id, tableAid, note)
1, 1, 'note1'
2, 1, 'note2'
3, 2, 'note1'

Should become:

Table A (id, typeId)
1, 6
2, 5
3, 2

Table B (id, tableAid, note)
1, 1, 'note1'
2, 1, 'note2'
3, 2, 'note1'
4, 1, 'type has changed'

Try to use OUTPUT clause.

Test tables and data:

CREATE TABLE A(
  id int NOT NULL PRIMARY KEY,
  typeId int NOT NULL
)

INSERT A(id,typeId)VALUES(1, 4),(2, 5),(3, 2)

CREATE TABLE B(
  id int NOT NULL IDENTITY PRIMARY KEY,
  tableAid int NOT NULL REFERENCES A(id),
  note varchar(50) NOT NULL
)

SET IDENTITY_INSERT B ON
INSERT B(id,tableAid,note)VALUES(1, 1, 'note1'),(2, 1, 'note2'),(3, 2, 'note1')
SET IDENTITY_INSERT B OFF

Using OUTPUT demo:

DECLARE @LogTable TABLE(tableAid int,note varchar(50))

UPDATE A
SET
  typeId=6
OUTPUT inserted.id,'type has changed'
INTO @LogTable(tableAid,note)
WHERE typeID=4

INSERT B(tableAid,note)
SELECT tableAid,note
FROM @LogTable

If you drop the foreign key in the table B then you can use OUTPUT directly into table B without @LogTable :

-- table B without FOREIGN KEY
CREATE TABLE B(
  id int NOT NULL IDENTITY PRIMARY KEY,
  tableAid int NOT NULL, --REFERENCES A(id),
  note varchar(50) NOT NULL
)

-- only one UPDATE with OUTPUT
UPDATE A
SET
  typeId=6
OUTPUT inserted.id,'type has changed'
INTO B(tableAid,note)
WHERE typeID=4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM