0

Assume that i have a table below

S.no   Question
 1      XXX 
 2      XXX
 3      XXX 
 4      XXX
 5      XXX
 6      XXX
 7      XXX
 8      XXX
 9      XXX
 10     XXX

and i want to get a random new result from the table and i dont want repeated id's and i have tried

SET @Q_ID=(SELECT Top 1 S.No from Table  order by NEWID())

but im getting sometimes repeated results , can anyone help me???

dazzling kumar
  • 584
  • 1
  • 8
  • 17

2 Answers2

2

You have to store your already returned result somewhere (for eaxample in another table) and then add a LEFT JOIN to check the value does not exist.

Here's the table

CREATE table AlreadyReturned
(
  Id int,
  UserName varchar(200)
)

And here's the code:

DECLARE @Q_ID int

// @Username will be passed as a paremeter of course, here
// it is set for simplicity
DECLARE @Username varchar(200)
SET @Username = 'test' 

WHILE @Q_ID IS NULL
 BEGIN
    SET @Q_ID=(
          SELECT Top 1 MyTable.[No] 
          FROM MyTable LEFT OUTER JOIN AlreadyReturned 
              ON MyTable.[No] = AlreadyReturned.Id AND AlreadyReturned.UserName = @UserName 
          WHERE AlreadyReturned.Id IS NULL order by NEWID())

    IF @Q_ID IS NULL
       DELETE FROM AlreadyReturned WHERE UserName = @Username
END 

INSERT INTO AlreadyReturned VALUES (@Q_ID, @Username)

SELECT @Q_ID

Take care this code is like a "Time Bomb", as it works until the AlreadyReturned table does not contain all the values that are present in the MyTable table

Paolo Costa
  • 1,989
  • 1
  • 12
  • 15
1

You will have to store whatever random question id was selected and exclude from selecting next time . Create a table QuestionsSelectedTable which stores already selected questions.

SET @Q_ID=(SELECT Top 1 S.No from Table  WHERE [S.No] NOT IN (SELECT Qid FROM QuestionsSelectedTable ) order by NEWID())
INSERT INTO QuestionsSelectedTable(Qid) VALUES(@QID)

Doing ORDER BY NEWID() selects randomly but is not guaranteed to return different result everytime as there is no dependency to the result which was generated before. Smaller the no of records in table , more are the chances of repeated results.

See here how NEWID() works

Community
  • 1
  • 1
Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133
  • yes ur's also similar to Paolo Costa but where i want to clear the AlreadyReturned tables for new users who are attending the questions – dazzling kumar May 05 '15 at 06:38