You must Sign In to post a response.
  • Category: SQL Server

    Randomly select rows in SQL Server

    Hi,

    I have around 100 questions in SQL Server. Out of these 100, I need only 20 questions randomly. That is on every click (Button Click) i need to get separate set of questions. Question repetition is allowed.

    What kind of loop I can use...

    Platform: C#.net windows application
  • #752090
    The following code returns a random number in a specific range (0 to 100):

    var rand = new Random();
    String myNumber = rand.Next(0, 100).ToString();

  • #752091

    Hai Ram prasad,
    In Sql Server, there is a built-in function called RAND which will give you the random number and based on the number, you can retrieve the question details.

    SELECT RAND(100)

    So you can get a number between 1 and 100. lets say you got 36, now based on this number, you can retrieve the question whose number is 36.
    Hope it will be helpful to you.


    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com

  • #752092

    Hi,

    You can do it by Random function like this

    protected void Page_Load(object sender, EventArgs e)
    {
    DataTable dt = Get20Questions();
    }
    public DataTable Get20Questions() {
    int GetQuestionNo = 20;
    DataTable dtAllQuestion = new DataTable();
    //Bind all 100 Question in dtAllQuestion datatable
    DataTable dt20Question = new DataTable();
    dt20Question.Columns.Add("Question");

    for (int i = 0; i < GetQuestionNo; i++)
    {
    Random rdmNo = new Random();
    int Random = rdmNo.Next(0, 20);

    dt20Question.Rows.Add(dtAllQuestion.Rows[Random]["Question"].ToString());
    }
    return dt20Question;
    }

    May be this is not exact solution which you are looking for but you have gave you it for only take a idea from it.
    Update this logic according to your need.


    Regards,
    Nirav Prabtani (Senior Web Developer)
    Email : niravjprabtani@gmail.com
    blog : niravprabtani.blogspot.in

  • #752094
    Hi,

    I am using below query. Hope, with the below code I will not face any problem...

    SELECT TOP (20) SLNo, Question, Option1, Option2, Option3, Option4, Department, CorrectAnswer, KeyArea FROM QuestionBank_Info ORDER BY NEWID()

    Thanks,
    Ram Prasad

  • #752191
    SELECT TOP (20) SLNo, Question, Option1, Option2, Option3, Option4, Department, CorrectAnswer, KeyArea FROM QuestionBank_Info ORDER BY NEWID()



    This Query should not have any issue as this is the correct way to do so.

    Thanks & Regards
    Anil Kumar Pandey
    Microsoft MVP, DNS MVM


  • Sign In to post your comments