簡體   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