I have a table that has id,cat & num fields.
Each cat has multiple ids, Num is 0
I need to create sp that will pick top 1 in each category and update field Num to 1.
id cat num
-- --- ---
1 A 0
2 A 0
7 B 0
6 B 0
2 C 0
7 C 0
I need pass cat in each statement
update tbl1 Set num=1 where id in
(select top 1 from tbl1 where cat='A')
update tbl1 Set num=1 where id in
(select top 1 from tbl1 where cat='B')
update tbl1 Set num=1 where id in
(select top 1 from tbl1 where cat='C')
BTW - you can usually (in 99.9% of cases) find a solution like this without using a cursor - cursors - you will find - especially on large db's so resource intensive that you might as well change the values manually.
[blue]DBomrrsm[/blue]
[blue]Software code, like laws and sausages, should never be examined in production[/blue][black] - [/black][purple]Edward Tenner[/purple]
Again, as dbomrrsm and I said, what defines top 1; lowest, highest or just the first record for each cat the query comes across? Does it matter which record gets updated, because the method you've shown would take a while if there are a lot of records.
You are correct. I've been so busy trying to learn the complicated stuff (I've reached the chapter on Cursors in my book), that I done forgot all the simple stuff.
Thank you for that correction, Pattycake245. I appreciate it.
Catadmin - MCDBA, MCSA
Remember, "Work" is a four letter word. And you know what your mother told you about using four letter words!
No problem, and if I were you I wouldn't spend much time on the cursors chapter, since you will hardly ever use it as 99% of the time a set-based solution will do the trick faster and more efficiently. Trust me, you'll see the hundreds of posts reiterating this point.
Yeah, but if I don't learn it, I'll run into that 1% of the time. Better to know it and know why it *won't* work then to not know it and be unable to come up with a solution.
Murphy really really likes me. @=)
Catadmin - MCDBA, MCSA
Remember, "Work" is a four letter word. And you know what your mother told you about using four letter words!
The Cert tests only require you to know the basics. And it's been over two years since I've been required to do anything other than DBA tasks and general (read simple) T-SQL Ad Hoc queries. Now that I'm in a Designer/DBA type job, I need to go back and relearn everything from the start forward.
Catadmin - MCDBA, MCSA
Remember, "Work" is a four letter word. And you know what your mother told you about using four letter words!
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.