我正在为在主表上执行的任何操作创建一个新触发器,我需要使用插入、更新和删除的触发器来更新我的本地表。但现在我在多行插入或更新期间面临问题。
我已经创建了触发器,但是对于多行插入和更新它不能正常工作。
CREATE TRIGGER [dbo].[TRG_pspartmas] ON [dbo].[ps_partmas]
AFTER INSERT
,UPDATE
,DELETE
AS
BEGIN
DECLARE @cmp_id VARCHAR(10)
DECLARE @sl_type VARCHAR(10)
DECLARE @sl_code VARCHAR(20)
DECLARE @sl_desc VARCHAR(200)
DECLARE @region_code VARCHAR(10)
DECLARE @tranYN VARCHAR(10)
DECLARE @IT_NO VARCHAR(50)
------------------------------------------------------------------------------Fetching recored from inserted
-- SELECT @cmp_id=cmp_id,@sl_type=cl_supp_code,@sl_code=part_code,@sl_desc=part_nm,@region_code=region_code,@tranYN=Stop_Order,@it_NO=IT_no
-- FROM inserted
--------------------------------------------------------------------------------if recored were deletd
SELECT @cmp_id = rtrim(ltrim(cmp_id))
,@sl_code = rtrim(ltrim(part_code))
,@sl_desc = rtrim(ltrim(part_nm)) --,@tranYN=rtrim(ltrim(Stop_Order))
FROM deleted
IF EXISTS (
SELECT *
FROM view_sl_code1
WHERE cmp_id = rtrim(ltrim(@cmp_id))
AND sl_code = rtrim(ltrim(@sl_code))
AND sl_type = @sl_type
)
BEGIN
BEGIN
DELETE
FROM view_sl_code1
WHERE cmp_id = rtrim(ltrim(@cmp_id))
AND sl_code = rtrim(ltrim(@sl_code))
AND sl_type = rtrim(ltrim(@sl_type))
END
END
SELECT @cmp_id = cmp_id
,@sl_type = cl_supp_code
,@sl_code = part_code
,@sl_desc = part_nm
,@region_code = region_code
,@tranYN = Stop_Order
,@it_NO = IT_no
FROM inserted
--@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IF EXISTS (
SELECT *
FROM view_sl_code1
WHERE cmp_id = rtrim(ltrim(@cmp_id))
AND sl_code = rtrim(ltrim(@sl_code))
AND sl_type = @sl_type
)
BEGIN
UPDATE view_sl_code1
SET sl_desc = rtrim(ltrim(@sl_desc))
,tranYN = rtrim(ltrim(@tranYN))
,actions = 'partmas_up'
,date_update = GETDATE()
WHERE cmp_id = rtrim(ltrim(@cmp_id))
AND sl_code = rtrim(ltrim(@sl_code))
END
------------------------------------------------------------------------------inserting new recored
IF NOT EXISTS (
SELECT *
FROM view_sl_code1
WHERE cmp_id = rtrim(ltrim(@cmp_id))
AND sl_code = rtrim(ltrim(@sl_code))
AND sl_type = @sl_type
)
BEGIN
INSERT INTO view_sl_code1 (
cmp_id
,sl_type
,sl_code
,sl_desc
,region_code
,tranYN
,IT_NO
,actions
,date_update
)
SELECT rtrim(ltrim(cmp_id))
,rtrim(ltrim(cl_supp_code)) AS sl_type
,rtrim(ltrim(part_code)) AS sl_code
,rtrim(ltrim(part_nm)) AS sl_desc
,rtrim(ltrim(region_code))
,CASE
WHEN Stop_Order = 'Y'
THEN 'N'
ELSE 'Y'
END AS tranYN
,IT_NO
,'partmas_in'
,getdate()
FROM dbo.ps_partmas
WHERE cmp_id = @cmp_id
AND part_code = @sl_code
AND cl_supp_code = @sl_type
END
--end
PRINT 'Trigger is activated'
END
我需要在本地表中捕获所有插入和更新的值。
你能建议吗?