1

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.

Filip De Vos
  • 11,568
  • 1
  • 48
  • 60
nfa379
  • 561
  • 3
  • 6
  • 13
  • Can you post your update statement that's taking 20+minutes to run? How many records is it updating? Just found out what [2Lakh][1] is – Brent D Aug 01 '11 at 18:44

2 Answers2

1

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
niktrs
  • 9,858
  • 1
  • 30
  • 30
0

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.

Community
  • 1
  • 1
Jacob
  • 41,721
  • 6
  • 79
  • 81
  • I did not mean looping through records using C# or Java but in the SQL Itself. I was just looking for ways to reduce the execution time as there are more than 2Lac records. It is taking 20mins using update+join – nfa379 Aug 01 '11 at 12:56
  • Ok, but looping through even in SQL will take mor time then the 20 minutes for update+join. Do you ahve appropriate indexes set up? – Jacob Aug 01 '11 at 13:11