• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 246
  • Last Modified:

Select Random row

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
johnywhite
Asked:
johnywhite
  • 2
1 Solution
 
Raynard7Commented:
select top1 * from tableName order by rand()
0
 
Aneesh RetnakaranDatabase AdministratorCommented:
select top1 * from tableName order by newID()
0
 
johnywhiteAuthor Commented:
How would I create the entire function?
0
 
Aneesh RetnakaranDatabase AdministratorCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now