2013-02-01 81 views
2

我有一個SQL Server中有一個PK(ID)和另一個(邏輯)主鍵由其他幾列(儘管沒有UNIQUE約束)的表。比方說,表PERSONPK = PERSON_ID,然後NAMESURNAMEAGE如何僅在一行受到影響時執行UPDATE?

我想這是可以說

UPDATE PERSON SET AGE = 43 WHERE NAME = 'XX' AND SURNAME = 'YYY' 

,並讓它執行僅當 '更新的行'= 1,否則(更比1排)完全沒有執行。問題是我不確定NAME和SURNAME是否唯一標識了一條記錄,而且我無法事先告知它。

想法?

+0

可能重複行查詢](http://stackoverflow.com/questions/3860975/sql-update-top1-row-query)和[用t-sql更新單行](http://stackoverflow.com/questions/2909118/更新單行與T - SQL)和[SQL查詢更新表中的最高1記錄](http://stackoverflow.com/questions/3855528/sql-query-to-update-top-1 - 記錄在表中) – Kermit

+0

@njk - 不是重複的;在這種情況下,用戶只希望在更新一行時執行,而不是簡單地更新第一條記錄。 – LittleBobbyTables

+0

@LittleBobbyTables我的歉意。 – Kermit

回答

1

這樣的事情應該這樣做。

UPDATE Person p1 
SET p1.AGE = 43 
WHERE NAME = 'XX' AND SURNAME = 'YY' 
AND NOT EXISTS (
    SELECT NULL FROM Person p2 
    WHERE p1.NAME = p2.NAME 
    AND p1.SURNAME = p2.SURNAME 
    GROUP BY p2.NAME, p2.SURNAME 
    HAVING COUNT(*) > 1) 
4

嘗試下面的查詢......它會幫助你

UPDATE PERSON 
SET AGE = 43 
WHERE NAME = 'XX' 
    AND SURNAME = 'YYY' 
    AND 1 = (SELECT COUNT(*) FROM PERSON WHERE NAME = 'XX' AND SURNAME = 'YYY) 
+0

我選擇了這個,因爲它是最短的一個:​​)。 Thx給所有人。 –

3

我把有條件的更新之前,而不是在where子句。

IF (SELECT COUNT(*) FROM PERSON WHERE NAME = 'XX' AND SURNAME = 'YYY') = 1 
UPDATE PERSON SET AGE = 43 WHERE NAME = 'XX' AND SURNAME = 'YYY' 
1
UPDATE Person p1 
SET p1.AGE = 43 
WHERE NAME = 'XX' AND SURNAME = 'YY' 
AND NOT EXISTS (
    SELECT NULL FROM Person p2 
    WHERE p1.NAME = p2.NAME 
    AND p1.SURNAME = p2.SURNAME 
    AND p1.ID <> p2.ID) 
1

不用編寫複雜的WHERE子句或IF語句,我通常只是包住整個事情在一個事務中,並檢查@@ ROWCOUNT:

BEGIN TRAN 
UPDATE PERSON SET AGE = 43 WHERE NAME = 'XX' AND SURNAME = 'YYY' 
IF @@ROWCOUNT > 1 ROLLBACK TRAN ELSE COMMIT TRAN 
[SQL更新TOP1的