Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • 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

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

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