Solved

Select Random row

Posted on 2006-11-16
4
221 Views
Last Modified: 2012-05-05
I want to create a function that selects rows based on the given criteria, then from those selected rows, I want it to randomly select one of them to return.
0
Comment
Question by:johnywhite
  • 2
4 Comments
 
LVL 35

Expert Comment

by:Raynard7
ID: 17962206
select top1 * from tableName order by rand()
0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 17962208
select top1 * from tableName order by newID()
0
 

Author Comment

by:johnywhite
ID: 17962237
How would I create the entire function?
0
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 500 total points
ID: 17962253
johnywhite,
> How would I create the entire function?

Here is the procedure,

CREATE PROCEDURE retRecords
AS
BEGIN
     select top1 * from tableName order by newID()
END


you can convert this to a function like this

CREATE FUNCTION udfUserRecords (
@Condition  varchar(100)
)
RETURNS @tab Table (i int , j varchar(1000)) ---- u need to modify this accordingly
AS
BEGIN
    INSERT INTO @tab
    SELECT TOP 1 i, j
    FROM urMasterTable
    WHERE i = @condition

    RETURn

END
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SQL Database - Move Tables from one Database to Another 4 43
push and Pull replication 31 46
SQL Syntax 6 36
SSRS Page Header from Group Data 2 21
Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question