我创建一个存储过程,以便返回我的表 这样的事情
CREATE PROCEDURE sp_returnTable
程序的身体
选择表*
结束
当我把这个SP的前端什么codeI需要编写检索它的DataTable对象。
我写了code这样的事情之一。我基本上想知道检索和存储表到数据表中的对象。我的所有查询正在运行,但我不知道如何检索表成一个DataTable直通存储过程
数据表dtable =新的DataTable();
cmd.Connection = _conn;
cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter的ADP =新的SqlDataAdapter(CMD);
OpenConnection的();
adp.Fill(dtTable);
CloseConnection();
下面这个code CMD已经绑定与存储过程的名称和参数。它会从存储过程返回我的DataTable
解决方案 字符串CONNSTRING =<您的连接字符串>中;
字符串SQL =你的SP的名字;
使用(SqlConnection的康恩=新的SqlConnection(CONNSTRING))
{
尝试
{
使用(SqlDataAdapter的DA =新的SqlDataAdapter())
{
da.SelectCommand =新的SqlCommand(SQL,康涅狄格州);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
的DataSet ds为新的DataSet();
da.Fill(DS,result_name);
数据表DT = ds.Tables [result_name];
的foreach(DataRow的行dt.Rows){
//操作数据
}
}
}
赶上(前的SQLException)
{
Console.WriteLine(SQL错误:+ ex.Message);
}
赶上(例外五)
{
Console.WriteLine(错误:+ e.Message);
}
}
从 Java的学校为例
I created a stored procedure so as to return me a table something like that
create procedure sp_returnTable
body of procedure
select * from table
end
When i call this sp on frontend what code i need to write to retrieve it in a datatable object.
I wrote code something like this one. I basically want to know retrieving and storing table into an object of datatable. My all queries are running but i dont know how to retrieve table into a datatable thru stored procedure
DataTable dtable = new DataTable();
cmd.Connection = _CONN;
cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
OpenConnection();
adp.Fill(dtTable);
CloseConnection();
here in this code cmd has been binded with stored procedure name and its parameters. Will it be returning me a datatable from stored procedure
解决方案string connString = "<your connection string>";
string sql = "name of your sp";
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
using(SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows) {
//manipulate your data
}
}
}
catch(SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch(Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Modified from Java Schools Example