我有以下TSQL语句将数据从一个数据库表插入到另一个数据库表中,如何使用Trigger管理这个?
Source表是[DISCS]
,目标表是,
[WIBOMH]
是主表,[WIBOMH]
是标题表,[WIBOMD]
是详细表
必须首先将订单插入[WIITEM]
,然后创建标题[WIBOMH]
我要解雇这个AFTER INSERT
。当我在DISC
表中添加一个新的DISC
时,我想触发以下插入语句
- 插入[WIITEM]
表---
INSERT INTO [WIITEM]
([itemId], [descr],[xdesc],[sales] ,[uOfM] ,[poUOfM] ,[uConvFact],[ref],[type],[status],[unitWgt] )
SELECT [itemId], [PURCHASE_DESCRIPTION], [SALES_DESCRIPTION], [sales] ,[uOfM] ,[poUOfM] ,[uConvFact],'TESTING', '2','0',[unitWgt]
FROM [DISCS]
WHERE [itemId] NOT IN (SELECT [itemId] FROM [WIITEM])
AND [makebuy]='Make';
- 插入[WIBOMH]
表---
DECLARE @d DATETIME = GETDATE();
INSERT INTO [WIBOMH]
([bomItem], [bomRev], [rollup], [mult], [autoBuild], [assyLead],[revCmnt],[author],[descr],[qPerLead],[lstMainDt],[revDate],[effStartDate],[ovride] )
SELECT DISTINCT [bomitem], 'B', '1', '1', '1', '3','TESTING','USER NAME','TESTING','0', FORMAT(@d, 'yyyy-MM-dd HH\:mm\:ss\.fff', 'en-US') AS 'Format#1',FORMAT(@d, 'yyyyMMdd' , 'en-US') AS 'Format#2',FORMAT(@d, 'yyyyMMdd' , 'en-US') AS 'Format#2','0'
FROM [DISCS]
WHERE [bomitem] IN (SELECT [ItemId] FROM [WIITEM] where type='2')
AND [bomitem] NOT IN (SELECT [bomItem] FROM [WIBOMH]);
- 插入[WIBOMD]
表---
INSERT INTO [WIBOMD]
([bomItem], [bomRev], [bomEntry], [partId], [qty],[cmnt],[srcLoc],[dType],[lead],[lineNbr])
SELECT [ItemID], 'B', [bomEntry], [partid], [qty],'TESTING','WSD-DS','0','0', [lineNbr]
FROM [DISCS]
WHERE [ItemID] IN (SELECT [ItemId] FROM [WIITEM] where type='2')
AND [ItemID] NOT IN (SELECT [bomItem] FROM [WIBOMD]);
我试过
INSERT INTO [MITESTCO].[WIITEM]
([itemId], [descr],[xdesc],[sales] ,[uOfM] ,[poUOfM] ,[uConvFact],[ref],[type],[status])
SELECT
[CALC STOCK PN], [PURCHASE DESCRIPTION], [SALES DESCRIPTION], [CALC STOCK PN] ,'EA' ,'EA' ,'1','SYNC FROM PDM', '2','0'--,[APPROX. WGT.]
FROM inserted
WHERE [MAKE / BUY]='Make' [CALC STOCK PN] NOT IN (SELECT [itemId] FROM [MIITEM] WHERE itemId NOT LIKE '*-CI');
但是我
无效对象[MITESTCO]。[WIITEM]
这里我得到了第一个触发器
create TRIGGER [dbo].[PNSETUP]
ON [dbo].[DISCS]
AFTER insert,UPDATE
AS
BEGIN
IF TRIGGER_NESTLEVEL() > 1
RETURN
SET ANSI_WARNINGS OFF;
INSERT INTO MITESTCO.dbo.WIITEM
([itemId], [descr],[xdesc],[sales] ,[uOfM] ,[poUOfM] ,[uConvFact],[ref],[type],[status])--,[unitWgt]
SELECT [CALC STOCK PN], [PURCHASE DESCRIPTION], [SALES DESCRIPTION], [CALC STOCK PN] ,'EA' ,'EA' ,'1','SYNC FROM PDM', '2','0'--,[APPROX. WGT.]
FROM [DISCS]
WHERE [CALC STOCK PN] NOT IN (SELECT [itemId] FROM MITESTCO.dbo.[WIITEM] WHERE itemId NOT LIKE '*-CI')
AND [MAKE / BUY]='Make';
SET ANSI_WARNINGS ON;
如何将下两个insert select语句添加到同一个触发器
答案 0 :(得分:0)
您可以在插入触发器后使用每次插入后更新计数。
答案 1 :(得分:0)
你需要一个触发器吗?您是否需要实时复制表格中的新行?
触发器将杀死表的插入性能。
考虑将一个DateLastCopied列添加到源表,然后每分钟添加一次
declare @now as datetime= getdate()
update sourcetable set DateLastCopied=@now where DateLastCopied is null
insert into targetTable(..)
select ...
FROM sourcetable where DateLastCopied=@now