Pregunta

I have few Parameter in my SQL Query which accepts only ' ' value it will not accept null, so I want to pass '' value as parameter how is that possible, below is my code which I am trying to do

param = new SqlParameter("@CodeNumber", SqlDbType.VarChar);
if (!string.IsNullOrEmpty(SearchCriteria.CodeNumber))
  {
     param.Value = SearchCriteria.CodeNumber;
  }
else
  {
    param.Value = DBNull.Value;
    //param.Value = ''; I want to pass something like this
  }
cmd.Parameters.Add(param);


param = new SqlParameter("@LicenseDate", SqlDbType.DateTime);
if (SearchCriteria.LicenseDate != null && SearchCriteria.LicenseDate != default(DateTime))
  {
      param.Value = SearchCriteria.LicenseDate;
  }
else
  {
     param.Value = DBNull.Value;
     //param.Value = ''; I want to pass something like this
   }
cmd.Parameters.Add(param);

I am not getting any error but in query it is not taking as ' '

¿Fue útil?

Solución 3

I modified my query and checking if @LicenseDate is null then setting value as empty in SP, and from the code behind i am passing DBNull.Value, which solved my problem for date param

Otros consejos

Try passing empty String as the parameter when the underlying field is varchar. For example, you could do this:

param = new SqlParameter("@CodeNumber", SqlDbType.VarChar);
 if (!string.IsNullOrEmpty(SearchCriteria.CodeNumber))
  {
   param.Value = SearchCriteria.CodeNumber;
  } 
 else
  {
   param.Value = String.Empty;    
  }
cmd.Parameters.Add(param);

For DateTime, SQL Server will treat inserting empty string to a DateTime column as inserting the value 1/1/1900 12:00:00 AM, as seen here. Therefore, in place of empty string, you could pass in this value of DateTime in C#, like so:

param = new SqlParameter("@LicenseDate", SqlDbType.DateTime);
 if (SearchCriteria.LicenseDate != null && SearchCriteria.LicenseDate != default(DateTime))
  {
   param.Value = SearchCriteria.LicenseDate;
  }
 else
  {
   param.Value = new DateTime(1900,1,1,0,0,0)
   }
cmd.Parameters.Add(param);

You can create the stored procedure with a default value like the following;

CREATE PROCEDURE [dbo].[SP] 
    @param1 varchar(512),
    @param2 varchar(50) = NULL 
AS

Then if you pass the value, the value passed through the param would be taken. It can be skipped from application (c# code) and if skipped the default NULL value would be taken.

So in this case, the @param2 can be skipped when not required from application.

If not null, instead of NULL, you can pass '', like the following

CREATE PROCEDURE [dbo].[SP] 
    @param1 varchar(512),
    @param2 varchar(50) = ''
AS
BEGIN
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top