August 30, 2008 at 8:18 pm
I have this stored procedure:
SELECT Name,NEWID()
FROM Persons
WHERE ADUserName = @ADUserName
UNION ALL
SELECT TOP 5 Name,NEWID()
FROM Persons
ORDER BY NEWID()
This works to an extent. However the 2nd query always returns the same 5 random records. If I run the 2nd query by itself, it always returns 5 different random records. How can I get this randomization to work for the 2nd query within the union, or is there another way to approach this? Thanks in advance.
August 30, 2008 at 9:05 pm
The Order BY you have affects the WHOLE query, UNION and all... you need to trick the 2nd query into a standalone query even in the presence of the UNION ALL... Like this...
SELECT Name, NEWID() AS ANewID
FROM Persons
WHERE ADUserName = @ADUserName
UNION ALL ----------------------------
SELECT *
FROM (SELECT TOP 5 Name,NEWID() AS ANewID
FROM Persons
ORDER BY NEWID())d
--Jeff Moden
Change is inevitable... Change for the better is not.
August 30, 2008 at 9:25 pm
AWESOME!! Thanks jeff
August 30, 2008 at 11:19 pm
Thanks for the feedback, Juan. 🙂
--Jeff Moden
Change is inevitable... Change for the better is not.
November 16, 2008 at 5:19 pm
Obrigada! 🙂
Thanks
November 16, 2008 at 5:27 pm
De nada!
--Jeff Moden
Change is inevitable... Change for the better is not.
May 3, 2011 at 9:15 am
you're awesome jeff thanks a lot 😀
May 17, 2011 at 6:31 pm
Thank you for the feedback :blush:... especially on such an old post.
Out of interest, what did you use this trick for?
--Jeff Moden
Change is inevitable... Change for the better is not.
May 18, 2011 at 6:39 am
Jeff Moden (5/17/2011)
@cassano7Thank you for the feedback :blush:... especially on such an old post.
Out of interest, what did you use this trick for?
My guess is on randomizing data. Let's see what he has to say :-P.
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply