我想知道这是否可行。我想仅在typeId等于我的值时才更新记录,如果是这种情况,则在表B中添加记录。
表A:
id (PK, int)
typeId (int)
表B:
id (PK, int)
tableAId (FK, int)
note (nvarchar)
我的SQL脚本:
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
上面的脚本看起来像我想要实现,但显然它是不正确的。在我的情况下如何做多件事?更新一个值并插入一个包含当前id的记录?
数据样本:
Table A (id, typeId)
1, 4
2, 5
3, 2
Table B (id, tableAid, note)
1, 1, 'note1'
2, 1, 'note2'
3, 2, 'note1'
应该成为:
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'
尝试使用OUTPUT
子句。
测试表和数据:
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
使用OUTPUT
演示:
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
如果你把外键放在表B
然后你可以直接使用OUTPUT
到没有B
的表@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