列名或提供的值数与表定义不匹配 - 无法识别根本原因

时间:2016-06-29 10:12:56

标签: sql-server vb.net visual-studio visual-studio-2010 vb.net-2010

获取错误

  

cmd.ExecuteNonQuery()

我当前的代码

Using con As New SqlConnection(sConString)
    Using cmd As New SqlCommand(
        "INSERT INTO MC_Entry VALUES(" &
        "@0,@1, @2, @3, @4, @5,@6,@7,@8,@9,@10,@11,@12,@13,@14,@15,@16,@17," &
        "@18, @19, @20, @21, @22,@23,@24,@25,@26,@27,@28,@29,@30,@31,@32,@33,@34," &
        "@35, @36, @37, @38, @39,@40,@50,@51,@52,@53,@54)", con)

        For MyIncremental = 0 To 54
            cmd.Parameters.AddWithValue("@" & MyIncremental, vValues(MyIncremental))
        Next MyIncremental

        'Debug.Print(UBound(vValues))
        'Debug.Print(LBound(vValues))
        'Debug.Print(Join(vValues, vbTab))


        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
    End Using
End Using

vValues的下限值= 0

vValues的上限值= 54

我的SQL服务器表中有55列没有增量字段,每个字段都可以接受Null值。

我不知道为什么我会收到此错误,因为一切似乎都很好......

  

列名或提供的值数与表定义不匹配。

有什么建议吗?

根据答案帖子,我终于在循环中进行了操作,以便将来不会遗漏必要的字符串。

For i = 0 To 54
    ReDim Preserve sfields(0 To i)
    sfields(i) = "@" & i
Next

sConcat = Join(sfields, ",")

Using con As New SqlConnection(sConString)
    Using cmd As New SqlCommand("INSERT INTO MC_Entry VALUES(" & sConcat & ")", con)

        For i = 0 To 54
            cmd.Parameters.AddWithValue("@" & i, vValues(i))
        Next i

        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
    End Using
End Using

1 个答案:

答案 0 :(得分:1)

表格中共有55列,但您遗漏了导致错误的@41@49的参数。

如下所示将解决您的问题

"INSERT INTO MC_Entry VALUES(" &
"@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17," &
"@18, @19, @20, @21, @22, @23, @24, @25, @26, @27, @28, @29, @30, @31, @32, @33," &
"@34, @35, @36, @37, @38, @39, @40, @41, @42, @43, @44, @45, @46, @47, @48, @49," &
"@50, @51, @52, @53, @54)", con)