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

            }
}
4

2 回答 2

0

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

于 2013-02-05T15:28:41.367 回答
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();
}

也试试这个链接:返回多个集合

于 2013-02-05T15:36:40.963 回答