Pages

Thursday, August 21, 2014

Get Random records on each fetch using TABLESAMPLE TIP #34

 

As discussed in previous tip which is TIP #33 we can get random result set by using NEWID function.

Now same can be achieve by using one more option which is called TABLESAMPLE.

We have following syntax for it

SELECT * FROM tableName TABLESAME (Number ROWS/PERCENT)

For example I am using same Adventureworks database and fetching top 10 records from Person table which should be different each time.

So, I will write following select query 

SELECT TOP(10) FirstName,Lastname,MiddleName from Person.Person TABLESAMPLE(10 Percent)

OR

SELECT TOP(10) FirstName,LastName, MiddleName From Person.Person TABLESAMPLE(1000 Rows)

When , I run it I got following records.

tableSample

So this is another a way of  fetching random numbers.

Enjoy !!!

RJ

No comments:

Post a Comment