我正在通过 OleDBConnection 读取 CSV 文件,检索那里某些字段的整数值并保存到 SQL DB。我有一个名为 Q3
的列,它是可为空的。
当我尝试以下操作时,效果很好:
create table #temp (num int);
insert into #temp (num) values (null);
但是,我在 asp.net 4.5 中有以下代码,它不起作用:
SQLDatabase sql = new SQLDatabase();
SQLParamList sqlParams = new SQLParamList();
int? Q3 = null;
Q3 = CheckNumericContent(r, dr, "Q3"); //Q3 empty cell for the row in csv.
sqlParams.Add("@Q3", Q3); //Q3 is still null here.
sql.ExecStoredProcedureDataTable("[spInsert_Data]", sqlParams);
CheckNumericContent
函数的代码在这里:
private int? CheckNumericContent(int r, DataRow dr, string columnname)
{
int ret = -1;
if (dr[columnname] != null && !String.IsNullOrEmpty(dr[columnname].ToString()))
{
try
{
if (!Int32.TryParse(dr[columnname].ToString(), out ret))
{
ErrorMessage = ErrorMessage + string.Format("Row {0}: {1) is not numeric.\n", r.ToString(), columnname);
}
}
catch (Exception ex)
{
ErrorMessage = ErrorMessage + "some error: "+ex.ToString();
}
return ret;
}
else
{
return null;
}
}
spInsert_Data 存储过程是 (Sql Server 2014):
CREATE PROCEDURE spInsert_Data
@Q3 int
AS BEGIN
insert into tblMyData (Q3) values (@Q3);
END
这段代码运行良好,除非 Q3 为空。当 Q3 为空时,这意味着 CSV 中的一行没有 Q3 的数据,它给出错误:
Procedure or function 'spInsert_Data' expects parameter '@Q3', which was not supplied.
错误的图片在下面。出了什么问题,我该如何解决?任何帮助将不胜感激!
最佳答案
您可以使用 DBNull.Value
。
int? Q3 = null;
Q3 = CheckNumericContent(r, dr, "Q3"); //Q3 empty cell for the row in csv.
if (Q3.HasValue)
{
sqlParams.Add("@Q3", Q3);
}
else
{
sqlParams.Add("@Q3", DBNull.Value)
}
sql.ExecStoredProcedureDataTable("[spInsert_Data]", sqlParams);
DBNull.Value
可用于在数据库中设置空值。来自docs :
If a database field has missing data, you can use the DBNull.Value property to explicitly assign a DBNull object value to the field.
关于c# - 如何通过 C# 将可空整数列的空值插入 SQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54244925/