Update a varchar field with null value - c#

I have a field clube varchar(50) that is by default NULL, and it it's not notnull so it accepts null values. What I need to know is, if I have a value already on this field and I want to make an Update and set it's value with null, how would I do that?
I tried to set null the value of a string but didnt worked.
IF some condition become true, I want to set this field as NULL by an Update.
And as obvious, if the condition become false, I will pass a value and NOT null value. So I need to do it using MySqlcommand Parameter. Like:
sql = "UPDATE usuarios SET nome = #nome";
cmd.CommandText = sql;
cmd.Parameter.Add(New MySqlParameter("#nome", MySqlDbType.VarChar)).Value = `variable`;
if the condition is true = variable = null else variable != null.

To set the value to null:
cmd.Parameter.Add(New MySqlParameter("#nome", MySqlDbType.VarChar)).Value = DBNull.Value;

Here's the answer I found:
cmd.Parameters.Add(new MySqlParameter("#nomeclube", MySqlDbType.VarChar)).Value = !String.IsNullOrEmpty(usr.Nome_Clube) ? (object)usr.Nome_Clube : DBNull.Value;

Simple. Just set it to NULL:
UPDATE table SET clube = NULL WHERE .....

Related

get all rows from db if parameter added to where clause is null

I have big select with where condition.
WHERE ADB.param1=#param
In Where I send param variable
SqlParameter param1Param = cmd.Parameters.AddWithValue("#param1", param1);
if (param1== null)
{
param1Param.Value = DBNull.Value;
}
This code works the following way.
When query executes it always checks for ADB.param1=param condition and when I send DBNull.Value it gets nothing from database.
But instead of that I want that
if param== null
then it pay no attantion to this condition and get all rows from database. How can I achive that ?
If you want to return all rows where the #param1 parameter is null use...
where (#param1 is null or ADB.param1 = #param1)
If you want to return only those rows where the column value of param is null use...
where ((#param1 is null and ADB.param1 is null) or ADB.param1 = #param1)
Here is one trick which doesn't even require changing your C# code:
WHERE ADB.param1 = COALESCE(#param, ADB.param1)
For non SQL NULL values, the #param must equal the ADB.param1 column. Otherwise, the WHERE clause would always be true, and would return all records.
I assume your query is WHERE ADB.param1=#param1
Try with WHERE (ADB.param1=#param1 OR #param1 IS NULL)

Null values are not inserted in Allow Nulls colums in C#

My query returns false when some values are null, but my table allows Null values.
What did I do wrong?
cmd.CommandText ="Insert into BusinessTbl(BName,BAddress,BEmail,BMobile,BPhone,Cat_Id)" +
"values(#bname,#baddress,#bemail,#bmobile,#bphone,#catid)";
cmd.Parameters.AddWithValue("#bname", b.BusinessName);
cmd.Parameters.AddWithValue("#name", b.BusinessAddress);
cmd.Parameters.AddWithValue("#bemail", b.BusinessEmail);
cmd.Parameters.AddWithValue("#bmobile", b.BusinessMobile);
cmd.Parameters.AddWithValue("#bphone", b.BusinessPhone);
cmd.Parameters.AddWithValue("#catid", b.ddlbcategory);
con.ExecuteNonQuery(cmd);
My Table
This is a vexing feature of ADO.NET parameters; basically:
cmd.Parameters.AddWithValue("#bname", ((object)b.BusinessName) ?? DBNull.Value);
cmd.Parameters.AddWithValue("#name", ((object)b.BusinessAddress) ?? DBNull.Value);
// etc
should fix you. If the .Value is null, the parameter isn't sent - it needs to be DBNull.Value. Alternatively, a tool like "Dapper" helps avoid this pain:
con.Execute(#"Insert into BusinessTbl(BName,BAddress,BEmail,BMobile,BPhone,Cat_Id)
values(#bname,#baddress,#bemail,#bmobile,#bphone,#catid)",
new { bname = b.BusinessName, ... , catid = b.ddlbcategory });
(which will parameterize correctly, including the nulls)

Make textbox default value equals to 0

I have set my textbox = 0
<p>Credit Balance: </p><asp:TextBox ID="txtCredit" runat="server" style="width:70px" Text = "0"></asp:TextBox>
and my code behind is this:
scn.Open();
SqlCommand cmd = new SqlCommand("SELECT CreditRequest FROM UserData WHERE Username=#Username", scn);
cmd.Parameters.Add("#Username", SqlDbType.NVarChar).Value = Session["New"];
object value = cmd.ExecuteScalar();
if (value != null)
{
txtCredit.Text = Convert.ToDecimal(value).ToString("#,##0.00");
}
What i want to happen is if it has value, it will display it. if none, default value is equal to 0. But i am receiving an error
Object cannot be cast from DBNull to other types.
I suspect, value is coming as DBNull, you could guard against DBNull using Convert.IsDBNull method.
if (!Convert.IsDBNull(value))
{
txtCredit.Text = Convert.ToDecimal(value).ToString("#,##0.00");
}
Instead of using null, use DBNull.
if(value != DBNull)
{
// update textbox
}
Things you should consider:
Instead of setting the text attribute, sent its VALUE.
Verify your value before converting it. You are comparing it from null, but it is a DBNull. Check this information in addition to your Null validation.
Good luck!

SQLCommand.CreateParameter.Value = DBNull.Value not returning results

I have code that creates a Null parameter like this
p = cmd.CreateParameter();
p.DbType = DbType.Int32;
p.ParameterName = strName;
p.Value = DBNull.Value;
cmd.Parameters.Add(p);
when I insert a record the SQLValue is set to {Null}
And the record is properly created with a Null value for the column.
When I select a record to try and retrieve a record with a Null value setting the parameter using the same approach above..once again the SQLValue for the parameter is {Null}
So same code same set up...but now it does not return the record. I cant retrieve any records when I want to create a parameter with a null value (p.Value = DBNull.Value;) . I get nothing back.
I know its not the query because if I change the parameter to one with a value I get that record back. Is there something I am missing to set the parameter to look for a null value? Everything I have seen has said to just do it that way.
As requested below is the query
Select * from view_full_class_nests
where parent_interface_class_pk = #parent_interface_class_pk
Also as noted this query works fine if the paramter is set with a value...only fails to retrieve if the value is DBNull.Value
DanD below provided useful link that gave me my answer
Need the query to be Select * from view_full_class_nests
where parent_interface_class_pk = #parent_interface_class_pk or #parent_interface_pk Is Null
You can't compare NULL in your where clause:
From https://msdn.microsoft.com/en-us/library/ms172138(v=vs.100).aspx:
Because null is considered to be unknown, two null values compared to each other are not considered to be equal. In expressions using arithmetic operators, if any of the operands is null, the result is null as well.
You will have to use ISNULL operator, see below for a previous answer that may help you:
Null value parameters in where clause in ado.net

SQLCommand SqlParameter Default Column Value in UPDATE C#

How to set Default Value as Value of SqlCommand SqlParameter?
SqlCommand is the class contained in System.Data.SqlClient
My Schema does not accept DBNull.Value as value
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1) { Value = DBNull.Value });
As lboshuizen points out, if your "schema" isn't taking null, or the parameter of the stored procedure or query cannot be null, trying to give it a null value will likely fail. In this case, you need to see why you are trying to set it to null if you know it doesn't accept it. I would surmise an empty string as opposed to null would work, or something else that is sensible.
The SqlParameterCollection property Parameters has an AddWithValue method:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
You can simply insert null and that will be handled for you:
command.Parameters.AddWithValue("#parameter", null);
If you cannot provide a null, you can provide something like an empty string:
command.Parameters.AddWithvalue("#parameter", "");
You also very rarely need to specify the data type using this mechanism.
If the schema doesn't accept null it indicates that the column is mandatory and requires a sensible value.
Using a default value for a column is a property of the schema.
So either alter the schema to provide a default.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
Choose a valid (not null) default value in your application code and use it as a value in the parameter.
const string default = "unknown";
...
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1)
{ Value = default });
Note: Changing the schema to accept NULL is considered cheating :-)

Categories