繁体   English   中英

检查更新数据是否与SQL Server中以前的数据相同

[英]Check if data for update is same as before in SQL Server

我有一个表Table1

 ID | RefID |  Answer | Points | 
----+-------+---------+--------+
 1  |   1   |    1    |   5    | 
 2  |   1   |    2    |   0    | 
 3  |   1   |    3    |   3    | 
 4  |   2   |    1    |   4    | 

我在具有相同结构的临时表Temp1中设置了一个结果集,并且仅当refID答案和点已更改时才更新Table1,否则应删除该记录。

我试过了:

update table1 
set table1.answer = temp1.answer,
    table1.points = temp1.points 
from table1 
join temp1 on table1.refid = temp1.refid 
where table1.answer != temp1.answer or table1.points != temp1.points

这是一个小提琴http://sqlfiddle.com/#!18/60424/1/1

但是,这不起作用,并且不知道如何添加删除条件。 期望的结果应该是表是否不相同。 (第二行回答2分3):

 ID | RefID |  Answer | Points | 
----+-------+---------+--------+
 1  |   1   |    1    |   5    | 
 2  |   1   |    2    |   3    | 
 3  |   1   |    3    |   3    | 
 4  |   2   |    1    |   4    | 

如果它们相同,则删除所有具有refID的记录。

temp1具有此数据时的说明

     ID  | RefID |  Answer | Points | 
     ----+-------+---------+--------+
     12  |   1   |    1    |   5    | 
     13  |   1   |    2    |   0    | 
     14  |   1   |    3    |   3    | 

编辑:添加另一个id列Questionid也通过在联接中添加它来解决更新。

现在的表结构为:

 ID | RefID |  Qid |Answer | Points | 
----+-------+------+-------+--------+
 1  |   1   |  10  |  1    |   5    | 
 2  |   1   |  11  |  2    |   0    | 
 3  |   1   |  12  |  3    |   3    | 
 4  |   2   |  11  |  1    |   4    | 

用于更新的SQL是:(小提琴http://sqlfiddle.com/#!18/00f87/1/1 ):

update table1 
set table1.answer = temp1.answer,
   table1.points = temp1.points 
from table1 
join temp1 on table1.refid = temp1.refid and table1.qid = temp1.qid 
where table1.answer != temp1.answer or table1.points != temp1.points;

SELECT ID, refid, answer, points 
FROM table1

如果数据相同,如何进行删除?

您需要在连接中再添加一个条件以完全匹配该列。请尝试此条件。

update table1 
set table1.answer=temp1.answer,
    table1.points=temp1.points 
from
table1 join temp1 on table1.refid=temp1.refid and **table1.ID=temp1.ID**
where table1.answer!=temp1.answer or table1.points!=temp1.points

我认为从我的理解来看,如果id是唯一的,则需要使用id而不是refid或两者都使用

我先删除,然后再更新。
这样做的原因是,一旦删除了三列相同的所有记录,您的更新语句就会变得更加简单-您只需要连接,而无需where子句:

DELETE t1
FROM table1 AS t1
JOIN temp1 ON t1.refid = temp1.refid
          AND t1.qid = temp1.qid
          AND t1.answer=temp1.answer
          AND t1.points=temp1.points 

UPDATE t1 
SET answer = temp1.answer,
    points = temp1.points 
FROM table1 AS t1 
JOIN temp1 ON t1.refid=temp1.refid 
          AND t1.qid = temp1.qid

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM