我对sql server中的触发器有疑问。所以我拿到了这张桌子:
状态表
InStatusID时间CarID
1 NULL 10
和另一个包含其他表中所有主键的表(包括我上面发布的那个):
车牌表
CarID InStatusID OutStatusID ColorID
1 1 2 9
在为car table插入数据时,我需要用其他表中的ID填充它们。但是,来自应用程序的GUI不需要用户插入InStatusID列。 我的解决方案是在Car Table Insert上触发,为In Status表插入新值,使用插入的CarID,然后插入In Status表时会有另一个触发器来更新car表的InStatusID在同一个CarID上。
现在我的触发器看起来像这样:
汽车插入触发器
CREATE TRIGGER [dbo].[TRG_Cars_InsertStatus] ON [dbo].[Cars.Cars]
AFTER INSERT
AS
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN
BEGIN TRY
DECLARE @ID int
SELECT @ID=i.CarID from inserted i
INSERT INTO [dbo].[Cars.InStatuses] ([Time],[Created],[LastModified],[CarID]) values (NULL,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,@ID)
INSERT INTO [dbo].[Cars.OutStatuses] ([Time],[Created],[LastModified],[CarID]) values (NULL,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,@ID)
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
END
状态/输出状态插入触发
CREATE TRIGGER [dbo].[TRG_OutStatus_InsertCarID] ON [dbo].[Cars.OutStatuses]
AFTER INSERT
AS
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRY
DECLARE @ID int
SELECT @ID=i.OutStatusID from inserted i
UPDATE [dbo].[Cars.Cars]
SET OutStatusID=@ID
FROM [dbo].[Cars.Cars] CAR
INNER JOIN [dbo].[Cars.OutStatuses] STA
ON CAR.CarID = STA.CarID
END
代码运行但有一个错误:每次更新汽车表时,汽车表上的每一行也都会被更新。我以为我已经通过使用JOIN ON解决了这个问题,但没有成功。有谁可以帮助我?
答案 0 :(得分:0)
根本不要把FK InStatusID放在桌子上。只需将FK CarID放在InStatusID
上你不需要将FK放在另一张桌子上因为它的1-1关系