从SQL数据库表中提取数据

时间:2012-05-17 18:41:14

标签: c# sql

我根据ID编号(1,2..20等)在SQL中存储的1-35个问题范围内拉出25个随机数,这样一来,用户参加考试就会得到问题的随机问题SQL中的池我试图让SQL参数在循环变量中递增“a”被用作将值输入到受尊重的数组中的键。

示例代码在

下面
    protected void Question_Fetch(int[] Mixed_Questions) 
    //this array is loaded with my mixed numbers between 1-35(no duplicates) the array length //is 25 
    {
        Question_String_list = new string[25];
        Question_Answers = new string[25];
        Num_Answers = new string[25];
        Types_Of_Question = new string[25];
        User_Answers = new string[25];
        isLocked = new string[25];

        using (SqlCommand Comd = new SqlCommand("SELECT Question_String, Question_Answer, Type_Of_Question, Possible_Answers FROM Question_Pool WHERE Question_ID = @Question_ID", Conn))
        {
            SqlParameter IDParam = Comd.Parameters.Add("@Question_ID", SqlDbType.Int);
            for (int a = 0; a < Mixed_Questions.Length; a++)
            {
                int Random_Number = Mixed_Questions[a];
                Comd.Parameters.AddWithValue("@Question_ID", Random_Number);
                Conn.Open();                                        
                SqlDataReader rdr = Comd.ExecuteReader();
                if (rdr.Read())
                {
                    IDParam = Mixed_Questions[a];
                    //Random_Number = Mixed_Questions[a];
                    //Comd.Parameters.AddWithValue("@Question_ID", Random_Number);
                    Question_String_list[a] = rdr.GetValue(0).ToString();
                    Question_Answers[a] = rdr.GetValue(1).ToString();
                    Types_Of_Question[a] = rdr.GetValue(2).ToString();
                    Num_Answers[a] = rdr.GetValue(3).ToString();
                    Conn.Close();
                }
            }
        }
        Answer_Controls();
        Init_Test_Details();
    }

1 个答案:

答案 0 :(得分:2)

提出35个随机问题的更好方法可能是做这样的事情:

select top 35 * from Question_Pool order by (newid())

这有效地将问题随机化,然后再考虑其中的35个问题。这样,您可以在一个查询中完成所有操作,而不是35个查询。