返回多个sql查询结果 - C#

时间:2013-02-05 15:23:29

标签: sql-server-2008 c#-3.0

我有以下方法运行大约20个SQL查询。将结果返回给客户的最佳方法是什么?

public int Results()
{
    using (var conn = GetConnection())
            using (var cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = @"SELECT TOP 1 stdent_number from Students";

                conn.Open();
                var result = (int)cmd.ExecuteScalar();

                cmd.CommandText = @"SELECT TOP 1 class_number from Classes";
        var number = (int)cmd.ExecuteScalar();

                cmd.CommandText = @"SELECT TOP 1 table from Tables";
        var table = (int)cmd.ExecuteScalar();

                cmd.CommandText = @"SELECT TOP 1 suite from Suites";
        var suite = (int)cmd.ExecuteScalar();

                 .....
                //I want to return result, number, table and suite so they can be populated on client
        //What is the best way to return? Should I create IEnumerable and add values to it and return
        //as IEnumerable or should these be returned all separately or as a dictionary?
        //Also this is just an example in real time I have at least 15 values from sql queries that I       //want to return

            }
}

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,您需要如何通过此功能将所有成功的查询数据传递回客户端。 我建议你创建自己的类(DTO的[数据传输对象]),从你的函数中将多个信息传递给Client。而不是使用Int的函数的返回类型。

答案 1 :(得分:0)

如果您不想创建一个proc,请尝试下面的

将所有查询传递给字符串变量,如下所示......

string sql = "SELECT TOP 1 stdent_number from Students; SELECT TOP 1 class_number from Classes; SELECT TOP 1 table from Tables; SELECT TOP 1 suite from Suites";

之后尝试如下..

using (SqlConnection conn = new SqlConnection(connection))
{
    var result,number,table;
    conn.Open();
            Cmd = new SqlCommand(sql, conn);
            SqlDataReader sqlReader = Cmd.ExecuteReader();
            while (sqlReader.Read())
            {
                result = dr[0].ToString();
            }

            sqlReader.NextResult();

            while (sqlReader.Read())
            {
                number = dr[0].ToString();
            }

            sqlReader.NextResult();

            while (sqlReader.Read())
            {
                table = dr[0].ToString();
            }

            sqlReader.Close();
            Cmd.Dispose();
            conn.Close();
}

另请尝试以下链接:Return multiple set

相关问题