2013-06-12 34 views
0

更新我有2個表。插入記錄,如果不存在,然後用身份證在一個查詢

create table Sales 
(CustomerKey int 
,ProductKey int 
,CustomersProductsKey int 
,SalesAmount decimal(19,4)) 

Create Table CustomersProducts 
(CustomersProductsKey int IDENTITY(1,1), 
CustomerKey int, 
ProductKey int, 
Attribute1 int, 
Attribute2 varchar(max)) 

目前,當我將數據添加到銷售表,我需要任何新的customerkey的ProductKey組合插入CustomersProducts表,然後用得到的CustomersProductsKey標識值更新銷售表。這工作。

反正是有,我可以在一個步驟做到這一點?我不知道合併是否可以在相同的步驟進行插入和更新。

我也可能只是看着這個錯誤的方式。

感謝,

編輯:

正如你可以想像,事實上,我需要使用代理鍵是設計的一部分。 BO報告需要它。否則根本就不需要CustomersProductsKey。

回答

0

如果只添加一個步驟,使其工作, 我認爲我們需要創建另一個表,並在新表中創建觸發器和CustomersProducts

create table CustomersSalesProducts 
(CustomerKey int 
,ProductKey int 
,SalesAmount decimal(19,4) 
,Attribute1 int 
,Attribute2 varchar(max)) 


create trigger test1 on CustomersSalesProducts After Insert 
as 
begin 
    insert Sales select CustomerKey , ProductKey , 0, SalesAmount from inserted  
    insert CustomersProducts select CustomerKey , ProductKey , Attribute1, Attribute2 from inserted  
end 
go 

create trigger test2 on CustomersProducts after insert 
as 
begin 
    Update Sales set CustomersProductsKey = inserted.CustomersProductsKey 
    from inserted , Sales 
    where inserted.CustomerKey = Sales.CustomerKey 
    and inserted.ProductKey = Sales.ProductKey  
end 
go 

測試腳本:

insert CustomersSalesProducts select 3,3,300,3,'Attribute2' 
+0

感謝答案。不幸的是,沒有觸發器允許。 –

相關問題