1

我通过从多个表中收集数据来补充我的业务对象,例如,

从 CaDataTable 中选择 *;
从 NyDataTable 中选择 *;
从 WaDataTable 中选择 *;

等等...(C# 3.5,SQL Server 2005)

我一直在使用批次:

    void BatchReader()
    {
        string sql = "Select * From CaDataTable" +
                     "Select * From NyDataTable" +
                     "Select * From WaDataTable";

        string connectionString = GetConnectionString();
        using (SqlConnection conn = new SqlConnection(connectionString)) {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            using (SqlDataReader reader = cmd.ExecuteReader()) {
                do {
                    while (reader.Read()) {
                        ReadRecords(reader);
                    }
                } while (reader.NextResult());
            }
        }
    }

我还对同一个连接使用了多个命令:

    void MultipleCommandReader()
    {
        string connectionString = GetConnectionString();
        string sql;
        SqlCommand cmd;
        using (SqlConnection conn = new SqlConnection(connectionString)) {
            conn.Open();  

            sql = "Select * From CaDataTable";
            cmd = new SqlCommand(sql, conn);
            using (SqlDataReader reader = cmd.ExecuteReader()) {
                while (reader.Read()) {
                    ReadRecords(reader);
                }
            }

            sql = "Select * From NyDataTable";
            cmd = new SqlCommand(sql, conn);
            using (SqlDataReader reader = cmd.ExecuteReader()) {
                while (reader.Read()) {
                    ReadRecords(reader);
                }
            }

            sql = "Select * From WaDataTable";
            cmd = new SqlCommand(sql, conn);
            using (SqlDataReader reader = cmd.ExecuteReader()) {
                while (reader.Read()) {
                    ReadRecords(reader);
                }
            }
        }
    }

这些技术中的一种是否明显优于另一种?另外,如果我在第二种方法中使用 MARS 会有收益吗?换句话说,是不是像在连接字符串中设置 MultipleActiveResultSets=True 一样简单,并收获很大的好处?

4

2 回答 2

2

如果每个表中的数据结构都相同,我会这样做:

Select *, 'Ca' Source From CaDataTable
union all
Select *, 'Ny' Source From NyDataTable
union all
Select *, 'Wa' Source From WaDataTable
于 2009-06-17T18:48:39.190 回答
0

如果没有实际安排这两个版本的时间,您只能推测....

我希望版本 1 (BatchReader) 会更快,因为您只需要一次往返数据库。版本 2 需要三个不同的往返行程 - 每个执行一次查询。

但再说一遍:你只能真正判断你是否测量。

马克

哦,PS:当然,在现实生活中,它也有助于限制返回的列,例如,不要使用SELECT *而是使用SELECT (list of fields)并保持该字段列表尽可能短。

于 2009-06-17T21:07:13.883 回答