Sunday, September 12, 2010

Random Records in SQL Server based on Where Clause

How to get random records in SQL Server based on Where Clause

Syntax

Select Top [No. of Random Records you want]  *
from
(
Select  Col1, Col2
from ActualTableName
where
Col1 Like '%SearchWord%'
) VirtualTable
ORDER BY NEWID()
Note: VirtualTable is table that doesn't exist in database, it is just a placeholder name.


Example
Select Top 1 *
from
(
Select QuestionId, QuestionTitle
from ForumQuestion
Where
ForumQuestion.QuestionTitle Like @SearchKeyword
) MyTable
ORDER BY NEWID()

No comments:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape