获取Null的SQL Server更新语句

时间:2017-03-21 11:28:54

标签: sql sql-server sql-update

UPDATE Newchat
 Set [Answered] = (Select b.[Answered]
      From Table1 b
      where  Newchat.CHAT_ID = b.[Chat ID]
      and Newchat.Chat_Date >= '2017-Feb-22' and Newchat.Chat_Date <= '2017-Feb-28');

每当我运行此代码时,除了这个日期之外,[已回答]的所有行都会变为空。 请提出建议。

我也尝试应用过滤器&#34; Newchat。[已回答]不为空&#34;

UPDATE Newchat
     Set [Answered] = (Select b.[Answered]
          From Table1 b
          where  Newchat.CHAT_ID = b.[Chat ID] and Newchat.[Answered] is not null
          and Newchat.Chat_Date >= '2017-Feb-22' and Newchat.Chat_Date <= '2017-Feb-28');

这也不起作用。

3 个答案:

答案 0 :(得分:1)

如果没有匹配项,则会获得NULL。大概你真的想要:

UPDATE nc
    Set [Answered] = b.[Answered]
    From NewChat nc join
         Table1 b
         on nc.CHAT_ID = b.[Chat ID] and
            nc.Chat_Date >= '2017-Feb-22' and nc.Chat_Date <= '2017-Feb-28';

这只会更新符合条件的行。

答案 1 :(得分:1)

这里有两个问题。内部的(在括号内)为正在进行更新的外部数据提供数据。您的问题是内部查询受日期限制,因此它仅提供这些日期的值。但外部查询更新了所有行 - NULL,其中没有来自内部查询的数据。

保持接近您设置查询的方式,在括号外移动日期限制应该可以为您提供所需内容 - 例如:

UPDATE Newchat
 Set [Answered] = ( Select b.[Answered]
      From Table1 b
      where  Newchat.CHAT_ID = b.[Chat ID] )
 WHERE Newchat.Chat_Date >= '2017-Feb-22' and Newchat.Chat_Date <= '2017-Feb-28';

答案 2 :(得分:0)

请尝试以下UPDATE声明:

UPDATE Newchat SET [Answered] = b.[Answered]
From Table1 b
WHERE Newchat.CHAT_ID = b.[Chat ID] AND DATEDIFF(DAY,Newchat.Chat_Date,'2017- 
02-22') <= 0 AND DATEDIFF(DAY,Newchat.Chat_Date,'2017-02-28') >= 0