我有两个名为
的表PROD_DET
( ID , PROD_SUMM_ID, TRANS_DATE, EMP_ID, PROC_ID , PCS)
和
PROD_SUMM
( ID , TRANS_DATE, EMP_ID, PROC_ID , PCS)
现在每当记录插入PROD_DET表时,
我想Insert
(如果唯一的TRANS_DATE,EMP_ID,PROC_ID的记录不可用)/ Update
(如果记录了唯一的TRANS_DATE,EMP_ID,PROC_ID可用)我的PROD_SUMM
表格为,
来自PROD_DET的唯一TRANS_DATE table应该放在PROD_SUMM表的TRANS_DATE中,
唯一的EMP_ID和唯一的PROC_ID应该进入他们的 各栏目 在PROD_SUMM表中
我试过了一个触发器,但没有达到标记, 找到下面的截图
脚本来创建表格 ~~~~~~~~~~~~~~~~~~~~~~
CREATE TABLE [dbo].[PROD_DET](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PROD_SUMM_ID] [int] NULL,
[TRAN_DATE] [date] NOT NULL,
[EMP_ID] [int] NOT NULL,
[PROC_ID] [int] NOT NULL,
[PCS] [smallint] NOT NULL,
CONSTRAINT [PK_PROD_DET] PRIMARY KEY CLUSTERED
( [ID] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
CREATE TABLE [dbo].[PROD_SUMM](
[ID] [int] IDENTITY(1,1) NOT NULL,
[TRAN_DATE] [date] NOT NULL,
[EMP_ID] [int] NOT NULL,
[PROC_ID] [int] NOT NULL,
[PCS] [int] NOT NULL,
CONSTRAINT [PK_PROD_SUMM] PRIMARY KEY CLUSTERED
( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
答案 0 :(得分:0)
看粗糙的工作。有问题请问。
Declare @tbl table([ID] [int] IDENTITY(1,1) NOT NULL,[TRAN_DATE] [date] NOT NULL,[EMP_ID] [int] NOT NULL,[PROC_ID] [int] NOT NULL,[PCS] [int] NOT NULL)
insert into PROD_DET
output inserted.TRANS_DATE, inserted.EMP_ID, inserted.PROC_ID , inserted.PCS into @tbl
values() -- for PROD_DET
merge PROD_SUMM as target
using select id,b.TRAN_DATE,b.PCS,a.EMP_ID,a.PROC_ID from @tbl a inner join
(select TRAN_DATE,sum(PCS) PCS from @tbl group by TRAN_DATE) b on a.TRAN_DATE=b.TRAN_DATE) as source
on target.TRANS_DATE=source.TRANS_DATE and target.EMP_ID=source.EMP_ID and target.PROC_ID =source.EMP_ID
when matched then
update
set TRAN_DATE=source.TRAN_DATE,EMP_ID=source.EMP_ID,PROC_ID=source.PROC_ID,PCS=source.PCS
when not matched then
insert (TRAN_DATE,EMP_ID,PROC_ID,PCS)
values(source.TRAN_DATE,source.EMP_ID,source.PROC_ID,source.PCS)