Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#&;SQL Server:将Excel范围解析到数据表中,但数据表返回为空_C#_Sql_Excel - Fatal编程技术网

C#&;SQL Server:将Excel范围解析到数据表中,但数据表返回为空

C#&;SQL Server:将Excel范围解析到数据表中,但数据表返回为空,c#,sql,excel,C#,Sql,Excel,我正在尝试将excel范围中的值保存到数据表中。然后,我将数据表解析为存储过程以保存到数据库中 System.Data.DataTable dt = new System.Data.DataTable(); dt.Columns.Add("Territory", typeof(string)); dt.Columns.Add("OptionID", typeof(string)); dt.Columns.Add("ProductClass", typeof(string)); dt.Column

我正在尝试将excel范围中的值保存到数据表中。然后,我将数据表解析为存储过程以保存到数据库中

System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Territory", typeof(string));
dt.Columns.Add("OptionID", typeof(string));
dt.Columns.Add("ProductClass", typeof(string));
dt.Columns.Add("Taken", typeof(string));

for (var idx = 7; idx < lastUsedRow; idx++)
{
    string Territory = territory;
    string optionID = ((string)Worksheet.Range["B" + idx].Value2);
    string ProductClass = ((string)Worksheet.Range["C" + idx].Value2);
    string Taken = ((string)Worksheet.Range["V" + idx].Value2);
}

dt.Rows.Add(optionID, Territory, ProductClass, Taken) //this is an issue it returns dt{}
SQL:

我得到这个错误:

无法将值NULL插入表'@dt'的'OPTION_ID'列中;列不允许空值。插入失败。表值参数“@dt”的数据不符合该参数的表类型

SQL Server错误为:515,状态:2该语句已终止


dt{}
似乎是空的,因此它不会在其中插入任何内容。当我进入调试模式时,option ID变量中有一个值-这是将行插入datatable的正确方法吗?我需要将创建的列和行映射到一起,然后解析到我的存储过程中。

旁注:您不应该在存储过程中使用
sp
前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用
sp.
并使用其他东西作为前缀,或者根本不使用前缀!你不认为你没有给dt添加任何东西吗?你有一个循环,变量的作用域就是这个循环。在循环之后,您有一个.Add(…)-并且还有一个OptionId,Territory似乎是反向的。我将使用SqlBulkCopy类来代替这样的SP,直接从Excel加载到SQL Server。
var connectionstring2 = ConfigurationManager.ConnectionStrings["SDYConString"].ConnectionString;
var cn2 = new SqlConnection(connectionstring2);

cn2.Open();

var cmd2 = new SqlCommand("dbo.sp_ui_sm_insertrows", cn2);

SqlParameter tvparam = cmd2.Parameters.AddWithValue("@dt", dt);
var da2 = new SqlDataAdapter(cmd2);

cmd2.CommandType = CommandType.StoredProcedure;

cmd2.ExecuteNonQuery();
cn2.Close();
CREATE PROCEDURE [dbo].[sp_ui_sm_insertrows]
    @dt AS tbl_type_lines READONLY
AS
BEGIN
    INSERT INTO dbo.tbl_newline (TERRITORY, OPTION_ID, PRODUCT_CLASS, TAKEN)
        SELECT 
            TERRITORY, OPTION_ID, PRODUCT_CLASS, TAKEN
        FROM @dt;
END