sql NextResult()多个结果集

Posted 南潇湘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql NextResult()多个结果集相关的知识,希望对你有一定的参考价值。

 

转自  http://blog.csdn.net/limlimlim/article/details/8626898

 

注意:当SQL语句中出现两条Select语句,例如:string sql = "select * from Employees;select * from TblClass";
可以用SqlDataReader的NextResult()来接收多个结果集
使用
do
{
}
while(reader.NextResult())

 

        static void Main(string[] args)
        {

            string constr = "Data Source=zxtiger;Initial Catalog=itcastcn;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(constr))
            {
                string sql = "select * from Employees;select * from TblClass";
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    con.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        do
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    //循环列
                                    for (int i = 0; i < reader.FieldCount; i++)
                                    {

                                        //根据索引,获取列名
                                        //reader.GetName(i);
                                        //获取当前列的数据类型
                                        string dbType = reader.GetDataTypeName(i);
                                        switch (dbType)
                                        {
                                            case "varchar":
                                            case "nvarchar":
                                            case "char":
                                            case "nchar":
                                                Console.Write(reader.GetString(i) + "\t");
                                                break;
                                            case "int":
                                                Console.Write(reader.GetInt32(i) + "\t");
                                                break;
                                        }
                                    }
                                    Console.WriteLine();
                                }
                            }
                        } while (reader.NextResult()); //当多个结果集的时候可以调用NextResult

                    }
                }
            }
            Console.WriteLine("ok");
            Console.ReadKey();
        }

以上是关于sql NextResult()多个结果集的主要内容,如果未能解决你的问题,请参考以下文章

Asp.net(C#) 获取 执行sql server 语句/存储过程后的 多个返回值?

如何将单个结果集从返回多个集的 SQL 存储过程保存到临时表?

在 Laravel 5.3 中从 SQL Server 获取多个结果集

SQL Server R 多个结果集

PL/SQL 新手 - 返回多个结果集问题

SQL 操作结果集 -并集差集交集结果集排序