2012-06-28 50 views
0

這是正確的方式做到這一點更新,是這樣說的:與SQL更新加入

UPDATE [log].codesEntered 
SET [log].codesEntered.countrycode = 
      (SELECT [user].[profile].countryCode 
      FROM [user].[profile] 
        INNER JOIN [log].codesEntered 
         ON [log].codesEntered.userid = [user].[profile].userid 
      WHERE [log].codesEntered.countryCode <> [user].[profile].countryCode 
        AND [log].codesEntered.campid = @campid 
        AND [log].codesEntered.portalid = @portalid 
        AND [user].[profile].countryCode <> '' 
        AND [user].[profile].countryCode <> '--') 

或者這樣說:

UPDATE [log].codesEntered 
SET [log].codesEntered.countrycode = [user].[profile].countryCode 
FROM [log].codesEntered 
     INNER JOIN [user].[profile] 
     ON [log].codesEntered.userid = [user].[profile].userid 
WHERE [log].codesEntered.countryCode <> [user].[profile].countryCode 
     AND [log].codesEntered.campid = @campid 
     AND [log].codesEntered.portalid = @portalid 
     AND [user].[profile].countryCode <> '' 
     AND [user].[profile].countryCode <> '--' 
+0

我正在使用SQL Server – user517406

+0

第二個選項在語法方面看起來很標準 - [MSDN](http://msdn.microsoft.com/en-us/library/ms177523.aspx) – whytheq

+0

嘗試訪問[此鏈接] (http://praveenbattula.blogspot.com/2009/05/how-to-write-inner-join-in-update-query.html)的語法和示例 –

回答

1

假設SQL Server中的第二個不達標SQL,如果多個連接的行可以匹配codesEntered行,則會導致不確定的結果。

相關的子查詢版本會在該事件中引發錯誤。如果沒有匹配,它也會設置countrycodeNULL

連接可能更有效。

如果您至少在SQL Server 2008上,您還可以查看MERGE而不是專有的UPDATE ... FROM語法。如果嘗試多次更新同一行,則會引發錯誤。

+0

+1完全同意 - 如果子查詢返回多個選項,然後它遇到了一個問題:選項2是標準問題...去那個 – whytheq

0

你可以嘗試s.t像這樣(我喜歡的方式):

UPDATE [log].codesEntered log 
SET [log].codesEntered.countrycode = (select countryCode from [user].[profile] where [user].[profile].userid = log.userid) 
WHERE log.userid in 
     (select [log].codesEntered.userid 
     from [log].codesEntered join [user].[profile] 
     on [log].codesEntered.userid = [user].[profile].userid 
     where [log].codesEntered.countryCode <> [user].[profile].countryCode 
     AND [log].codesEntered.campid = @campid 
     AND [log].codesEntered.portalid = @portalid 
     AND [user].[profile].countryCode <> '' 
     AND [user].[profile].countryCode <> '--') 

這種方法也適用於其他DMBS如Oracle。

+1

你的最後一句似乎暗示在'UPDATE'查詢中使用'FROM'是錯誤的 - 我使用它很多 - [MSDN](http://msdn.microsoft.com/en-us/library/ms177523.aspx) – whytheq