2个字段更新sql server中的困难

时间:2014-12-31 11:15:09

标签: sql-server

我有以下2个表格:

create table Customer
( 
    item_ID int,
    Customer_id int,
    order_id int, 
    Datestamp datetime
)

create table tempTable
(
    item_id int, 
    Customer_id int,
    order_id int
)

我希望仅在Customer.Customer_ID不为空且Customer.order_id时才更新tempTable.Customer_IDtempTable.order_id,其值分别为tempTable.Customer_IDCustomer.Customer_ID为null(第二列的条件相同,即tempTable.order_ID不为空且Customer.order_ID为空时)。

我还想更新该更新的日期

这是我试过的查询:

UPDATE Customer
SET 
   Customer_ID = T.Customer_ID,
   order_id = T.order_id,
   DateStamp = GetDate()
FROM    
   tempTable T
INNER JOIN
   Customer C On T.item_ID = C.item_ID
WHERE   
   (T.Customer_ID is not null OR T.order_id is not null)
   AND (C.Customer_ID is null OR C.order_id is null)

此查询更新了更多行,因为该子句不是100%正确。

例如,当C.Customer_ID不为空且T.order_id为空时,即使C.Customer_ID不为空,它也会更新C.order_id

有没有办法在一个查询中实现目标?

由于

3 个答案:

答案 0 :(得分:1)

使用ISNULL(),

 UPDATE C
    SET    Customer_ID =ISNULL(c.Customer_ID,T.Customer_ID),
           order_id = ISNULL(c.order_id,T.order_id),
           DateStamp = Getdate()
    FROM   tempTable T
           INNER JOIN Customer C
                   ON T.item_ID = C.item_ID 
  WHERE c.Customer_ID IS NULL OR c.order_id IS NULL

答案 1 :(得分:0)

请尝试

UPDATE  
    Customer
SET    
    Customer_ID = CASE WHEN (C.Customer_ID is null And T.Customer_ID is not null) THEN T.Customer_ID ELSE Customer_ID END,
    order_id = CASE WHEN (C.order_id is null And T.order_id is not null) THEN T.order_id ELSE order_id END,
    DateStamp = GetDate()
FROM   
    tempTable T
    Inner Join Customer C On T.item_ID = C.item_ID
WHERE  
    (C.Customer_ID is null And T.Customer_ID is not null)
    Or   
    (C.order_id is null And T.order_id is not null)

答案 2 :(得分:0)

试试这个..使用Case Statement

UPDATE C
SET    Customer_ID = CASE
                       WHEN T.Customer_ID IS NOT NULL
                            AND c.Customer_ID IS NULL THEN T.Customer_ID
                       ELSE c.Customer_ID
                     END,
       order_id = CASE
                    WHEN T.order_id IS NOT NULL
                         AND c.order_id IS NULL THEN T.order_id
                    ELSE c.order_id
                  END,
       DateStamp = Getdate()
FROM   tempTable T
       INNER JOIN Customer C
               ON T.item_ID = C.item_ID 
WHERE  T.Customer_ID IS NOT NULL
        OR T.order_id IS NOT NULL

如果您使用Sql Server 2012+,请使用此功能。

UPDATE C
SET    Customer_ID = IIF( T.Customer_ID IS NOT NULL AND c.Customer_ID IS NULL, T.Customer_ID, c.Customer_ID),
       order_id = IIF( T.order_id IS NOT NULL AND c.order_id IS NULL, T.order_id, c.order_id),
       DateStamp = Getdate()
FROM   tempTable T
       INNER JOIN Customer C
               ON T.item_ID = C.item_ID 
WHERE  T.Customer_ID IS NOT NULL
        OR T.order_id IS NOT NULL