June 7, 2011 at 8:21 am
So here is my question when using a loop like below what is the best way to merge or union the results? And is there a better way to pull the same results below?
Thanks Guys
GO
declare @x int
SET @x = 1
While (@x <= 30)
begin
select TOP 2 * from dbo.table1
where dbo.table1.doctype = @x
order by doctype
set @x = @x + 1
END
June 7, 2011 at 8:49 am
It really depends on what you're trying to do.
If you absolutely have to loop through results and get them into a single resultset, the best way is usually to insert them into a temp table inside the loop, then select from the temp table once you exit the loop.
However, avoiding a loop in the first place is usually much easier and almost always MUCH better.
For this one, instead of a loop, using BETWEEN 1 AND 30 in the Where clause would solve the problem better than a loop. However, I'm assuming this is pseudocode and your actual issue is somewhat more complex. If so, care to post it?
- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
Property of The Thread
"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon
June 7, 2011 at 8:59 am
sweet i didn't know about the BETWEEN.
this actually got what i wanted for this piece. Ok to lay this all out for the big picture. I am working on a conversion for the company in which the apps are old crap.
Just bad code one app auto fills the SSN or TIN column if you do not put one in PITA the others are the app didn't force input consistancy, so know i have to fix it so the new product we are getting will work correctly. There is more than that, but all the same deal. I am having to use multiple DB's to try and match records and then correct the bad field. Then start the process over again for the next bad field. Quite the project for a newbie DBA.
June 7, 2011 at 9:08 am
Definitely sounds like more fun than I usually allow myself to experience. 😛
If you aren't familiar with Between, are you familiar with using "In" in Where clauses, to filter a set of results?
- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
Property of The Thread
"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon
June 7, 2011 at 9:34 am
GSquared (6/7/2011)
Definitely sounds like more fun than I usually allow myself to experience. 😛If you aren't familiar with Between, are you familiar with using "In" in Where clauses, to filter a set of results?
hahaha fun, right. I don't think i have used IN i may have, but do not remember.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply