Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
daniel50096230
Yak Posting Veteran
99 Posts |
Posted - 2012-05-23 : 03:57:23
|
I have the following query, and wondering how to write in a cursor.1) Select * From Master2) Loop through every rows, check the column Company_ID.3) If Company_ID = '1' Then Update Master1 Set Status = 'A' If Company_ID = '2' Then Update Master2 Set Status = 'A'May I know how can I loop those rows and update the field accordingly?Thanks. |
|
Lumbago
Norsk Yak Master
3271 Posts |
Posted - 2012-05-23 : 04:07:09
|
First of all: whenever you think that you need to do something in sql server in a loop, think again. Loops/cursors are the devil! In 99.9% of the cases there are better and more efficient ways to do it.In your case, these queries will solve your problem:UPDATE a SET Status = 'A'FROM Master1 a INNER JOIN Master b ON a.Company_ID = b.Company_IDWHERE a.Company_ID = '1'UPDATE a SET Status = 'B'FROM Master2 a INNER JOIN Master b ON a.Company_ID = b.Company_IDWHERE a.Company_ID = '2' - LumbagoMy blog-> http://thefirstsql.com |
 |
|
daniel50096230
Yak Posting Veteran
99 Posts |
Posted - 2012-05-23 : 04:17:11
|
Yes... I need a cursor. The example I provided is just a sample. My actual query is required more checking and insert to more different table accordingly, so a cursor loop is required. |
 |
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2012-05-23 : 07:38:33
|
quote: I have the following query, and wondering how to write in a cursor.
quote: Yes... I need a cursor. The example I provided is just a sample. My actual query is required more checking and insert to more different table accordingly, so a cursor loop is required.
I'm gonna be grumpy here and complain about wasting Lumbago's time on a few points:1. You post a query, saying you need a cursor for it2. You get a solution that doesn't require a cursor3. You then say, "A-ha! Tricked you! That's not the query I'm using!"4. And then argue that yes you do need a cursor, since you so easily deceived us with your trick query.Feel free to do any of the following:1. Post your actual query and leave nothing out.2. Use Lumbago's sample to write your own version without cursors.3. Write your own cursor version without our help. |
 |
|
daniel50096230
Yak Posting Veteran
99 Posts |
Posted - 2012-05-23 : 20:33:23
|
I had complete the query on my own...I will not wasting your time but I am appreciate if you will not wasting my time as well... |
 |
|
|
|
|