[英]Unable to pass parameter to the sql Date type to stored procedure from c# code
I have stored procedure in which I am selecting the records by comparing two dates. 我有存储过程,通过比较两个日期来选择记录。 From C# code I am passing parameters to the stored procedure but getting error 从C#代码中,我正在将参数传递给存储过程,但出现错误
Failed to convert parameter value from a String to a DateTime. 无法将参数值从字符串转换为DateTime。
My SQL Server stored procedure is : 我的SQL Server存储过程是:
ALTER PROCEDURE Select
@fromDt date = null,
@toDt date = null,
@flag int
AS
BEGIN
SET NOCOUNT ON;
if @flag = 1
begin
SELECT xxx,xxx,xxx from xxx where Status <> 'Complete'
end
else
begin
SELECT xxx,x,xxx from xxx where Status <> 'Complete' and Date >= @fromDt and Date < @toDt
end
END
GO
My code which queries to table is : 我查询表的代码是:
protected void btnFilter_Click(object sender, EventArgs e)
{
DoProcess(Convert.ToString(dtFrom.SelectedDate.ToString("yyyyMMdd")), Convert.ToString(dtTo.SelectedDate.ToString("yyyyMMdd")), 0);
}
private void DoProcess(string fromDt,string toDt, int flag)
{
SqlConnection connection = GeneralMethods.GetConnection();
SqlCommand selectCommand = new SqlCommand();
DataTable dtVendors = new DataTable();
try
{
// set command object properties
selectCommand.Connection = connection;
selectCommand.CommandType = System.Data.CommandType.StoredProcedure;
selectCommand.CommandText = "Select";
// check if from date and to dates are not null then set parameters to stored procedure.
if (!string.IsNullOrEmpty(fromDt))
{
selectCommand.Parameters.Add("@fromDt", SqlDbType.Date).Value = fromDt;
selectCommand.Parameters.Add("@toDt", SqlDbType.Date).Value = toDt;
}
// @flag is 1 then do not compare dates if 0 then compare to and from dates.
selectCommand.Parameters.Add("@flag", SqlDbType.Int).Value = flag;
// open the connection execute the select command.
connection.Open();
// load data into data table.
dtVendors.Load(selectCommand.ExecuteReader());
connection.Close();
if (dtVendors.Rows.Count > 0)
{
grdVendors.DataSource = dtVendors;
grdVendors.DataBind();
}
}
catch (Exception ex)
{ }
finally
{
// finally close the connection if open and release the resources
if (connection.State == System.Data.ConnectionState.Open)
connection.Close();
connection.Dispose();
selectCommand.Dispose();
dtVendors.Dispose();
}
}
How would I tackle the error? 我该如何解决错误?
Why you pass date parameter as string? 为什么将日期参数作为字符串传递?
selectCommand.Parameters.Add("@fromDt", SqlDbType.Date).Value = DateTime.Parse(fromDt);
or better 或更好
selectCommand.Parameters.Add("@fromDt", SqlDbType.Date, DateTime.Parse(fromDt));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.