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
Solved

Select Random row

Posted on 2006-11-16
4
214 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

829 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