Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter value to SQL stored proc of an optional string in asp.net

I have a search page, which has Date text field. The user may or may not populate this field. But the field is a parameter of a SQL stored proc that gets called to execute the search query.

When I walk through the code (and the Date field is blank), I get an error that the value could not be converted to DateTime

How can I convert a null value to DateTime, since the parameter is expected by the query?

cmdSearch.Parameters.Add(new SqlParameter("@StartDate", SqlDbType.DateTime));
cmdSearch.Parameters["@StartDate"].Value = Convert.ToDateTime(txtStartDate.Text.Trim());
like image 978
user279521 Avatar asked Jan 21 '23 21:01

user279521


2 Answers

If you set the parameter in the SQL proc as an optional parameter, by supplying a default value

CREATE PROCEDURE MyProc
...
@StartDate datetime = null,
....

them you can just omit sending that parameter from the c# code

DateTime result;
if (DateTime.TryParse(txtStartDate.Text, out result))
{
   cmdSearch.Parameters.Add(new SqlParameter("@StartDate", SqlDbType.DateTime));
   cmdSearch.Parameters["@StartDate"].Value = result;
}

If the parsing of the text field is unsuccessful, the parameter is not added in the parameter list, and the database uses the default value.

Also, using DateTime.TryParse(..) prevents dealing with exceptions.

like image 135
SWeko Avatar answered Jan 25 '23 15:01

SWeko


Wrap an if statement around the whole thing and test to see if String.IsNullOrEmpty(txtStartDate.Text)

EDIT

This is what I meant by, "whole thing" - apologies for not being clearer

if (!String.IsNullOrEmpty(txtStartDate.Text))
    cmdSearch.Parameters["@StartDate"].Value = Convert.ToDateTime(txtStartDate.Text.Trim());
else
    cmdSearch.Parameters["@StartDate"].Value = DateTime.MinValue;
like image 34
Neil Knight Avatar answered Jan 25 '23 14:01

Neil Knight