簡體   English   中英

如何將此sql server游標轉換為基於set的速度?

[英]How to convert this sql server cursor to set-based for speed?

如果一個表中的條件為真,則我必須插入多個表中,即

Person

tableID      PersonUniqueNumber
1               123
2               1234
3               121
4               12
5               113333

和另一張桌子

RentedHousesDetail

HouseId(tableId)      HouseName         HouseLocation    ISOK
   1                     A                  CA            NO
   2                     B                  DT            NULL
   3                     C                  NY            NULL
   4                     D                  CA        
   5                     E                  CA

和其他表

表加利福尼亞

表STATUSGREEN

因此,對於每個人來說,我必須查看他在RentedHousesDetail中的住所是否為CA,然后我必須在表CALIFORNIAHOUSE和STATUSGREEN中單行插入RentedHousesDetail.ID,並將RentedHousesDetail.ISOK列更新為NO。

表中有數千行,所以我寫了一個游標,例如

DECLARE variables

DECLARE cursorName CURSOR -- Declare cursor

LOCAL SCROLL STATIC

FOR

select PERSON.ID of those rows only where we have CA in RentedhouseDetails

OPEN cursorName -- open the cursor

FETCH NEXT FROM cursorName
INTO variables

WHILE @@FETCH_STATUS = 0

BEGIN

   FETCH NEXT FROM cursorName

   FOR EACH ROW that we have from cursor, insert into CALIFORNIAHOUSE and STATUSGREEN and update RentedHousesDetail.ISOK to NO

END

CLOSE cursorName -- close the cursor

DEALLOCATE cursor

請告訴我可以在Person和Rentedhousedetails表的數千行上使用光標嗎? 如何將其轉換為基於集合的速度運算?

我認為這里不需要使用游標。 首先,您必須選擇那些行的PERSON.ID,只有在Rentedhouse中有CA的地方

select p.id from Person p JOIN RentedHousesDetail r ON p.ID=r.ID 
where r.HouseLocation='CA'

然后將所有記錄插入CALIFORNIAHOUSE和STATUSGREEN表

像這樣

 Insert into CALIFORNIAHOUSE 
 select p.id from Person p JOIN RentedHousesDetail r ON p.ID=r.ID
 where r.HouseLocation='CA'

Insert into STATUSGREEN 
select p.id from Person p JOIN RentedHousesDetail r ON p.ID=r.ID
where r.HouseLocation='CA'

並且最后更新表RentedHousesDetail,其中HouseLocation ='CA'為'NO'

像這樣

update RentedHousesDetail set ISOK='NO' from Person p JOIN RentedHousesDetail r ON p.ID=r.ID
where r.HouseLocation='CA'

如果使用臨時表,則非常簡單。 沒有理由為此使用游標,並且以下內容的性能應超過基於游標的解決方案。

顯然,您將需要填寫偽代碼的空白。

Create Table #PersonIDs (PersonID int Not Null Primary Key Clustered);

Insert Into #PersonIDs 
Select Person.ID --- of those rows only where we have CA in RentedHouseDetails

Insert Into CALIFORNIAHOUSE
Select PersonID From #PersonIDs;

Insert Into STATUSGREEN
Select PersonID From #PersonIDs;

Update rhd
   Set ISOK = 'No'
   From RentedHousesDetail As rhd
   Join #PersonIDs On rhd.PersonID = #PersonIDs.PersonID;

Drop Table #PersonIDs;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM