开发者

Is NULL function different between SQL and VS 2005 (C#)?

开发者 https://www.devze.com 2023-03-12 12:49 出处:网络
I have demonstrate following SQL between SQL and VS 2005: update expbill set convrate=null where transID=2

I have demonstrate following SQL between SQL and VS 2005:

update expbill set convrate=null
where transID=2
and companyID=114

The above T-SQL is working fine on SQL Server and updates the rows as NULL, but the same transaction is not working in VS 2005, using this SQL query:

string update_exp = " update expbill set convrate = " + null + "" 开发者_如何学编程+
                " where companyID = '" + label1.Text + "'" + 
                " and invno = '" + textBox1.Text + "'";
SqlCommand updated_cmd  = new SqlCommand(update_exp , con);
updated_cmd.ExecuteNonQuery();

The above SQL query throws an error

Incorrect syntax near the key words “where”

I want to know that if the same SQL statement works in SQL but not in Visual Studio. Is there any difference of NULL function between SQL and VS 2005??


For the record:

string update_exp = @"
update expbill set convrate=@rate
where companyID=@cid
and invno=@iid";
SqlCommand updated_cmd  = new SqlCommand(update_exp , connection);
updated_cmd.Parameters.AddWithValue("rate", DBNull.Value);
updated_cmd.Parameters.AddWithValue("cid", label1.Text);
updated_cmd.Parameters.AddWithValue("iid", textBox1.Text);
updated_cmd.ExecuteNonQuery();

This will keep you safe. DO NOT CONCATENATE TEXT TO MAKE SQL. If that is typical of your coding style, I need you to realise that your code is dangerously exposed and can be abused and broken accidentally or maliciously. Pain. Lots of pain.


NULL is a keyword/symbol in SQL

string update_exp = " update expbill set convrate = NULL " +

The c# null is very different

Edit:

The equivalent would be DBNull.Value but I've never tried to concatenate it...


Just do this. You don't have to pass in a c# null. Just use SQL's.

string update_exp = " update expbill set convrate = null +
                    " where companyID='" + label1.Text + "'"+ 
                    " and invno='" + textBox1.Text + "'";

Both mean "nothing". But if you pass C#'s null into a string object, your built-up SQL statement would have read

update expbill set convrate = where companyid = 'somevalue' and invno = 'someOthervalue'

Hence the "Incorrect syntax near 'WHERE'"


Change to:

string update_exp = " update expbill set convrate = null "+
                " where companyID='" + label1.Text + "'"+ 
                " and invno='" + textBox1.Text + "'";


The problem is SQL interpret a text, and (as Piotr Auguscik said) null converts to empty string, your SQL will be broken in the convertion, it is not about the null, it is about the SQL text creation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号