插入表而不创建重复记录

时间:2015-01-08 15:39:49

标签: sql sql-server

我有以下5个表:

tblCustomer

CustomerID   CustomerName   
 -------     ------------
   1         ABC Bank     
   2         Chase Bank      

tblOrderType

OrderTypeID    OrderTypeName   
 ----------    ------------
   1           Assignment     
   2           LienRelease
   3           Document Retrieval 

tblActivity

ActivityID        ActivityName   
 ----------       ------------
   1              Received     
   2              Keyed
   3              Printed
   4              Delivered To Customer

tblOrder

OrderID        CustomerID      OrderTypeID   LoanNumber
 ----------    ------------    -----------   ----------
   1           1                1            45584565
   2           1                1            45566856
   3           1                1            45565584
   4           1                1            45588545

tblOrderActivity

OrderID        ActivityID    ActivityDate
 ----------    -----------   ----------
   1           1             2007-04-16 8:34:00 AM
   1           2             2007-04-16 9:22:00 AM  
   1           3             2007-04-16 9:51:00 AM 
   1           4             2007-04-16 4:14:00 PM  
   2           1             2007-04-16 8:34:00 AM
   2           3             2014-12-16 10:33:09 AM
   3           1             2007-04-16 8:34:00 AM
   3           2             2007-04-16 9:22:00 AM
   3           3             2007-04-16 9:51:00 AM
   3           4             2007-04-16 4:14:00 PM
   4           1             2007-04-16 8:34:00 AM
   4           2             2007-04-16 9:22:00 AM
   4           3             2007-04-16 9:51:00 AM 

为保护目的,信息已被更改。所以说我需要能够为每个分配订单创建新的文档检索订单因为每天都可以添加新的分配订单,所以我需要确保可以在不创建重复条目的情况下随时运行查询。每个新订单还必须在tblOrderActivity表下具有当前日期/时间的已接收活动。我完全失去了,希望你能帮助我。

2 个答案:

答案 0 :(得分:0)

如果您使用SQL SERVER 2008或更高版本,则可以使用SQL MERGE语句。

这允许您比较源表和目标表,并在匹配时(或不匹配)执行适当的操作。在您的情况下,当您没有按订单ID匹配时,您希望插入目标表。

MERGE tblOrderActivity AS dst
USING tblOrder AS src
ON dst.OrderID = src.OrderID AND dst.ActivityID = 1
WHEN NOT MATCHED BY TARGET THEN
INSERT (OrderID, ActivityID, ActivityDate)
VALUES (src.OrderID, 1, GETDATE());

替代方法(可能比合并声明更快)

INSERT tblOrderActivity (OrderID, ActivityID, ActivityDate)
SELECT o.OrderID, 1, GETDATE()
FROM tblOrder AS o
LEFT JOIN tblOrderActivity AS oa ON o.OrderID = oa.OrderID AND oa.ActivityID = 1
WHERE oa.OrderID IS NULL

答案 1 :(得分:0)

将回答第二部分

“每个新订单还必须在tblOrderActivity表下具有当前日期/时间的已接收活动。”

您将在tblOrder表上创建一个触发器,将新记录插入到tblOrderActivity表中

CREATE TRIGGER tblOrder_ins
ON tblOrder
FOR INSERT
AS
INSERT INTO tblOrderActivity (OrderID, ActivityID, ActivityDate)
SELECT OrderID, 1 AS ActivityID, GETDATE()
FROM INSERTED

至于第一部分,也许你应该展示你使用的查询,它将更好地理解你需要什么。