我在通過外部應用程序將數據插入數據庫時嘗試更新記錄時遇到問題。在觸發器上更新插入的記錄
我需要記錄從應用程序的用戶被插入取值MinimumStock
從表AERO_LOCATIONSTOCKMIN
上它們是父位置和資產類型
LOCATIONSTOCKMINID ASSETTYPEID LOCATIONID MINIMUMSTOCK
54000000001 54000000043 43200000357 12.00
54000000002 54000000043 43200000883 6.00
這是目的:當用戶嘗試要在Asset
表中插入記錄(通過外部應用程序),觸發器必須檢查用戶是否已爲該Asset
選擇位置。如果是這樣,觸發器必須檢索所選位置的父級位置,並檢查是否存在爲此AssetType
定義的庫存最小值以及此父級位置。
如果全部滿足,則觸發器必須將字段UDFText01
設置爲上表中定義的最小庫存。
這是我到目前爲止嘗試過的。觸發器正在檢查需求,但在嘗試更新並引發以下錯誤時失敗:
The transaction ended in the trigger. The batch has been aborted
。
我試圖以許多方式修改UPDATE語句,但它們都引發了相同的錯誤消息。
編輯
繼@Sean Lannge的建議我已經編輯了扳機,以管理多個刀片。觸發器不再顯示錯誤消息,但更改(插入)未保存到數據庫中。
ALTER TRIGGER [spectwosuite].[TRI_ASSET_STOCKMIN] ON [spectwosuite].[ASSET]
FOR INSERT AS
BEGIN
IF (UPPER(USER) != 'SPECTWOREPLENG')
DECLARE @assettypeid numeric(15);
DECLARE @assetid numeric(15);
DECLARE @locationid numeric(15);
DECLARE @parentlocationid numeric(15);
DECLARE @stockmin numeric(9,2);
DECLARE @mistock varchar(100);
DECLARE crs_ROWS CURSOR FOR
SELECT ASSETID, ASSETTYPEID, LOCATIONID
FROM inserted;
OPEN crs_ROWS;
FETCH NEXT FROM crs_ROWS INTO @assetid, @assettypeid, @locationid
WHILE (@@FETCH_STATUS = 0)
BEGIN
SELECT @parentlocationID = ParentLocationID FROM Location
LEFT JOIN Asset ON Asset.LocationID = Location.LocationID
WHERE Asset.LocationID = @locationid;
IF NOT EXISTS
(SELECT * FROM Location LEFT JOIN INSERTED AS i ON Location.LocationID = i.LocationID
WHERE Location.LocationID = i.LocationID)
BEGIN
RAISERROR ('Please fill the Location for the Asset.',16,1);
ROLLBACK;
END
ELSE
IF EXISTS (SELECT MinimumStock FROM AERO_LOCATIONSTOCKMIN
WHERE AssetTypeID = @assettypeid AND LocationID = (SELECT ParentLocationID FROM Location WHERE LocationID = @locationID))
BEGIN
SELECT @stockmin = MinimumStock FROM AERO_LOCATIONSTOCKMIN
WHERE AssetTypeID = @assetTypeID AND LocationID =
(SELECT ParentLocationID FROM Location WHERE LocationID = @locationID);
SELECT @mistock= CONVERT(varchar(100),@stockmin);
--RAISERROR (@mistock,16,1);
UPDATE spectwosuite.ASSET
SET UDFText01 = @mistock
FROM
INSERTED I
INNER JOIN spectwosuite.ASSET T ON
T.AssetID = I.AssetID
--UPDATE spectwosuite.ASSET SET UDFText01 = @mistock
-- FROM spectwosuite.ASSET AS A INNER JOIN inserted AS I
-- ON A.AssetID = I.AssetID;
END
ELSE
RAISERROR ('The parent Location for the Asset Type doesn't have minimum stock defined',16,1);
ROLLBACK;
FETCH NEXT FROM crs_ROWS INTO @assetid, @assettypeid, @locationid;
END;
CLOSE crs_ROWS;
DEALLOCATE crs_ROWS;
END;
是哪個領域的用戶輸入數據到表中的列UDFText01一個(使用外部應用程序嗎?) –
@ S.Krishna是的。 – equisde
我認爲在這種情況下,您將需要使用'而不是'觸發器。看到這個SO http://stackoverflow.com/questions/5341584/sql-server-after-insert-trigger-update-another-column-in-the-same-table –