开发者

Help Needed SQL - Parsing through a 2 Lac+ records

I have a Customer table with 200.000+ records which i have to loop through and check for a condition(on a particular column) and update the "IsPremiumUser" Column to TRUE. what is the best way to go about it?

I see i can achieve this in two ways

  1. Use Join and Update
  2. Loop through each record and update it.

I am using SQL Server2008.

Update: I did not mean looping through records using C# or Java but in the SQL Itself. I am looking for ways to reduce the execution time as there are more than 200.000 records. It is taking 20 mins using update+join

Update2: Here are the queries.

MERGE pref.personpreference AS T
USING (SELECT PR.PersonID,PR.PersonroleId from personrole PR ) as S
ON (T.PersonRoleID = S.PersonRoleID)
WHEN MATCHED THEN 
    UPDATE SET T.SDRPERSONID = S.PersonId;



UPDATE PP 
SET PP.SDRPersonID = PR.PersonID
FROM PREF.PersonPreference PP JOIN PersonRole PR
ON PP.PersonRoleID = PR.PersonRoleID

Notes: Merge is taking 17 mins and update 20 mins to execute. But i see the number of records modified开发者_开发知识库 differ by some 1000 between these statements.


If the column is on the same table then use an UPDATE statement with a WHERE condition in which you will define the rows to be updated.

UPDATE Customers
SET isPremiumUser = 1 -- true
WHERE some_column operator some_condition 

eg

WHERE friend_members > 10


Always use database commands instead of looping through a bunch of records and issuing UPDATE statements every time a row meets your condition. It will be much, much faster and only 2-3 lines of SQL instead of 10-20 lines of java/c#/whatever-code.

Have a look at SQL update query using joins for an example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜