Solved

Select Random row

Posted on 2006-11-16
4
227 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

737 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