2017-08-11 60 views
0

我在SQL Server 2012中兩個表結構如下:批量更新存儲過程與選擇,並加入在where子句

customer 
- internalId 
- listingStatus 
- inactive 
membership 
- custIntneralId 
- regDate 

這裏是我使用SELECT語句:

USE [dbOne] 
SELECT DISTINCT(t1.internalId) 
FROM customer AS t1 
INNER JOIN membership AS t2 ON t1.internalId = t2.custInternalId 
WHERE t1.internalId = t2.custInternalId 
AND t1.inactive = 0 
AND t1.listingStatus = '' 

這裏是UPDATE語句,如果我要使用循環按行插入行:

UPDATE customer SET listingStatus = '6' WHERE internalId=custInternalId 

因爲我婉噸做批量更新而不是逐行,我試圖寫一個存儲過程,我可以觸發進行批量更新。我嘗試了幾種不同的方式來編寫它,但一直無法讓它們工作。以下是我已經嘗試了一個存儲過程的例子:

USE [dbOne] 
UPDATE customer 
SET customer.listingStatus = '6' 
FROM customer AS t1 
INNER JOIN membership AS t2 ON t1.internalId = t2.custInternalId 
WHERE t1.internalId = t2.custInternalId 
AND t1.inactive = 0 
AND t1.listingStatus = '' 

我也試圖把select語句的UPDATE語句的WHERE子句中,沒有工作裏面。我看不到我錯過了什麼,任何人都可以幫助我?

回答

0

在SQL Server中,您可以將表別名指定爲更新目標。你不必前綴列名,因爲你只能使用一個單一的更新來更新一個表:

UPDATE t1 
SET  custentity_iahp_listing_status = '6' 
FROM customer AS t1 
JOIN MembershipPurchaseHistory AS t2 
ON  t1.internalId = t2.custInternalId 
WHERE t1.inactive = 0 
     AND t1.custentity_iahp_listing_status = '' 

無需重複ON子句WHERE子句中,這就是被照顧。

請注意,在您的SELECT查詢中,您加入了membership表,但更新加入了MembershipPurchaseHistory表。這可能會產生不同的結果。