如何在 SQL 服务器中保存 "NULL" 而不是空格?

How to save "NULL" instead of spaces in SQL Server?

这很简单我有一些文本框要填写并提交给SQL服务器,其中一些可能是空白的,所以每当我运行查询时,我都会得到一堆空格数据库中单词 Null..

我的查询是这样的:

 var qry = "INSERT INTO tablename  (Text,Trans, ..)
                              Values ('"TextBox1.text "','" TextBox2.text, ..)";
db.Query(qry);

您可以使用 NULLIF:

INSERT INTO tablename  (Text,Trans, ..)
Values (NULLIF('" + TextBox1.text + "', ''), NULLIF('" + TextBox2.text + "', ''), ..)";

更好的选择是做类似...

SqlCommand cmd = new SqlCommand("INSERT INTO tablename  (Text,Trans) Values (@Text, @Trans)");
cmd.Parameters.Add(new SqlParameter("@Text" , string.IsNullOrEmpty(TextBox1.text) ? (object)DBNull.Value : TextBox1.text);
cmd.Parameters.Add(new SqlParameter("@Trans", string.IsNullOrEmpty(TextBox2.text) ? (object)DBNull.Value : TextBox2.text);