我想从存储过程返回虚拟表,我想在c#.net中的数据集中使用它。我的程序有点复杂,无法找到如何返回表并在数据集中设置它
以下是我要修改的程序:
ALTER PROCEDURE [dbo].[Procedure1]
@Start datetime,
@Finish datetime,
@TimeRange time
AS
BEGIN
SET NOCOUNT ON;
declare @TimeRanges as TABLE (SessionStart datetime, SessionEnd datetime);
with TimeRanges as (
select @Start as StartTime, @Start + @TimeRange as EndTime
union all
select StartTime + @TimeRange, EndTime + @TimeRange
from TimeRanges
where StartTime < @Finish )
select StartTime, EndTime, Count( Test.ScenarioID ) as TotalPeaks
from TimeRanges as TR left outer join
dbo.Test as Test on TR.StartTime <= Test.SessionStartTime and Test.SessionCloseTime < TR.EndTime
group by TR.StartTime, TR.EndTime
END
答案 0 :(得分:50)
试试这个
DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
sqlComm.Parameters.AddWithValue("@Start", StartTime);
sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
答案 1 :(得分:8)
我应该告诉你基本步骤和休息取决于你自己的努力。您需要执行以下步骤。
不要忘记打开和关闭连接。请点击此link获取更多信息。
答案 2 :(得分:2)
您可以在全局级别声明SqlConnection
和SqlCommand
个实例,以便您可以在整个课程中使用它。连接字符串位于Web.Config
。
SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
现在,您可以使用以下方法将值传递给存储过程并获取DataSet
。
public DataSet GetDataSet(string paramValue)
{
sqlcomm.Connection = sqlConn;
using (sqlConn)
{
try
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
// This will be your input parameter and its value
sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);
// You can retrieve values of `output` variables
var returnParam = new SqlParameter
{
ParameterName = "@Error",
Direction = ParameterDirection.Output,
Size = 1000
};
sqlcomm.Parameters.Add(returnParam);
// Name of stored procedure
sqlcomm.CommandText = "StoredProcedureName";
da.SelectCommand = sqlcomm;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
}
}
catch (SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
return new DataSet();
}
以下是配置文件
中的连接字符串示例<connectionStrings>
<add name="SqlConnector"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>