2013-02-19 62 views
0

我有一個查詢,我在MS-SQL中編寫,必須檢查,以查看有關客戶端的信息是否已經在表中插入之前。如果一個實體已經改變,那麼該行將被插入。問題是我可以在where子句中結合運算符嗎?現在我有一個查詢,看起來像這樣:sql組合多個運營商

select * from @Temp c 
where exists (select * from Clients c2 
      where (c.ClientId = c2.ClientId and c.ClientFName <> c2.FirstName) 
      or (c.ClientId = c2.ClientId and c.ClientLName <> c2.LastName) 
      or (c.ClientId = c2.ClientId and c.ClientAddress <> c2.Address) 
      or (c.ClientId = c2.ClientId and c.ClientCity <> c2.City) 
      or (c.ClientId = c2.ClientId and c.ClientState <> c2.State) 
      or (c.ClientId = c2.ClientId and c.ClientZip <> c2.Zip) 

有什麼優勢或劣勢編寫這樣的查詢:

select * from @Temp c 
where exists (select * from Clients c2 
      where (c.ClientId = c2.ClientId 
      and (c.ClientFName <> c2.FirstName 
      or c.ClientLName <> c2.LastName 
      or c.ClientAddress <> c2.Address 
      or c.ClientCity <> c2.City 
      or c.ClientState <> c2.State 
      or c.ClientZip <> c2.Zip))) 

對我來說,這兩個查詢工作,但什麼是最好的方式寫這個?

回答

1

任何時候你可以消除冗餘,這是一件好事。第二種方式獲勝。 :)

順便說一句,讓我們回答一個更好的問題,你沒有問,假設@tempClients加載,以便您可以找到有問題的記錄。你可以這樣做:

SELECT * FROM Clients 
WHERE clientid in (
    SELECT clientid from (select distinct * from Clients) t 
    GROUP BY clientid HAVING count(*) > 1) 

(這也消除了null小號比較混亂)

1

我不太知道確切的問題是在這裏。但是,兩者看起來都很好 - 我更喜歡第二個從可讀性的角度來看,但是這是偏好。

表現明智,我不認爲你會注意到一個區別。

2

實際上,如果您查看這兩個查詢的查詢計劃,您可能會發現優化程序將它們還原爲相同的事物。如果沒有,那麼你會選擇提供最佳性能的版本(查詢計劃),但這兩者是等價的,優化器可能會注意到並利用它。

我注意到,如果任何列允許空值,那麼該列的比較是不充分的。你需要更類似的東西:

OR c1.ClientAddress <> c2.ClientAddress 
OR (c1.ClientAddress IS NULL AND c2.clientAddress IS NOT NULL) 
OR (c1.ClientAddress IS NOT NULL AND c2.clientAddress IS NULL)