How to manager empty string to null?

  • Thread starter Thread starter Bostonasian
  • Start date Start date
B

Bostonasian

How do I manage empty string to null?
Do I have to code like following?
if(txtBoxFirstName.text == "")
cmd.Parameters.Add("@FirstName",DBNull.Value):
else
cmd.Parameters.Add("@FirstName",txtBoxFirstName.text):

Or are there better ways?

Also, I am curious about how to manage for integer as well.
 
Hmm.. I don't quite follow it.
Basically I am using stored procedure and if it passes empty string it
won't return proper result.
SQL goes like this:

SELECT first_name,last_name
FROM customers
WHERE 1 = CASE
WHEN @first_name is null THEN 1
WHEN @first_name is not null AND first_name =
@first_name THEN 1
ELSE 0 END

If empty string is passed, no result will return though my intention is
to view all records.

So right now I am writing code as the example on my 1st post.
 
Hmm.. I don't quite follow it.
Basically I am using stored procedure and if it passes empty string it
won't return proper result.
SQL goes like this:

SELECT first_name,last_name
FROM customers
WHERE 1 = CASE
WHEN @first_name is null THEN 1
WHEN @first_name is not null AND first_name =
@first_name THEN 1
ELSE 0 END

Therefore, if empty string is passed, no result will return though my
intention is to view all records.
 
You can just not pass any parameter. And put the following code in your
stored procedure:

@FirstName varchar(20) = NULL

This sets the default value to null if its not provided.

If you need to pass a value anyway, try the following:

In your vb code:

cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@FirstName", sqlDbType.Varchar, 20).Value = DBNull.Value

cmd.ExecuteNonQuery -- or -- MySqlDataReader = cmd.ExecuteReader

In your prodecure:

-- Procedure declaration goes here
@FirstName varchar(20)
AS
IF @FirstName is NULL
BEING
--Code if null
END
ELSE
BEGIN
--Code if is not null
END

Ps.: This code was not tested, but is something like that.
 
Back
Top