C# 通过DataSet 获取SQL 存储过程返回的多个结果集(tables)
测试数据:Northwind
链接地址: https://files.cnblogs.com/files/louiszh/NorthWind.zip
首先创建一个测试存储过程:
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE id = object_id ('pr_test')) DROP PROCEDURE pr_test go CREATE PROCEDURE pr_test AS SELECT TOP 4 * FROM Customers SELECT TOP 4 * FROM Employees GO EXEC pr_test
返回两个结果集:
在C#代码中通过DataSet集合获取存储过程结果集:
using System; using System.Data; using System.Data.SqlClient; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string connStr = "Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=root"; SqlConnection conn = null; conn = new SqlConnection(connStr); conn.Open(); string sql = "exec pr_test"; SqlDataAdapter sda = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); sda.Fill(ds); DataTable dt_customer = ds.Tables[0]; DataTable dt_employee = ds.Tables[1]; Console.WriteLine(dt_customer.Rows.Count); } } }
查看 DataSet是包含两个Table的: