执行两个INSERT语句

时间:2014-03-26 16:56:32

标签: sql .net sql-server vb.net ado.net

我有两个单独的INSERT语句,我想一个接一个地运行, 第一个成功运行,但似乎它甚至没有得到第二个声明任何想法为什么?

Try
    con.Open()
    cmd.ExecuteNonQuery()
    resultSQL.ForeColor = Drawing.Color.Green
    resultSQL.Text = "Successfully Saved"

Catch ex As Exception
    Response.Write(ex.Message)
    resultSQL.ForeColor = Drawing.Color.Red
    resultSQL.Text = ex.Message

Finally

End Try

INSERT 2未运行:

strQuery = "INSERT INTO [SD_EPOS_Entry]" _
    & " ([Trade_Activity_Code] " _
    & " VALUES " _
    & " (@Trade_Activity_Code1)"

cmd = New SqlCommand(strQuery)

cmd.Parameters.AddWithValue("@Trade_Activity_Code1", tcodeVar)

Try

    con.Open()
    cmd.ExecuteNonQuery()
    resultSQL.ForeColor = Drawing.Color.Green
    resultSQL.Text = "Successfully Saved2"

Catch ex As Exception

    Response.Write(ex.Message)
    resultSQL.ForeColor = Drawing.Color.Red
    resultSQL.Text = ex.Message

Finally

2 个答案:

答案 0 :(得分:1)

在你的第二个问题中,马上似乎缺少一个括号:

strQuery = "INSERT INTO [SD_EPOS_Entry]" _
        & " ([Trade_Activity_Code] " _
        & " VALUES " _
        & " (@Trade_Activity_Code1)"

应该是:

strQuery = "INSERT INTO [SD_EPOS_Entry]" _
        & " ([Trade_Activity_Code]) " _
        & " VALUES " _
        & " (@Trade_Activity_Code1)"

我还建议您正确处理您创建的任何SqlCommandSqlConnection个实例,方法是使用Dispose()方法或在Using语句中声明它们。< / p>

如果您说第二个查询甚至没有达到,请在运行时使用调试器跟踪您的代码并查看它停止的位置。那就是提供一些线索。

<强>更新

这应该在一个操作中执行两个INSERT语句:

strQuery = "INSERT INTO [SD_T_Code]" _
    & " ([Trade_Activity_Code]) " _
    & " VALUES " _
    & " (@Trade_Activity_Code)" _
    & ";INSERT INTO [SD_EPOS_Entry]" _
    & " ([Trade_Activity_Code]) " _
    & " VALUES " _
    & " (@Trade_Activity_Code)"

Dim strMessage As String = "Successfully saved"
Dim resultColor As Drawing.Color = Drawing.Color.Green

Using cmd = New SqlCommand(strQuery, con)
    cmd.Parameters.AddWithValue("@Trade_Activity_Code", tcodeVar)

    Try
        con.Open()
        cmd.ExecuteNonQuery()
        resultSQL.ForeColor = Drawing.Color.Green
        resultSQL.Text = "Successfully Saved"
    Catch ex As SqlException
        strMessage = ex.Message
        resultColor = Drawing.Color.Red
    Finally
        con.Close()
    End Try
End Using

// Write results outside of db operation
Response.Write(strMessage)
resultSQL.ForeColor = resultColor
resultSQL.Text = strMessage

当然,上面假设存在一个未实现的,未打开的con连接变量。

请注意,它也只捕获SqlException。在这里捕捉基本Exception似乎对我不利。

第二次更新:

如果上述代码不起作用,则问题可能是由Sql Trigger引起的。

答案 1 :(得分:0)

代码中未显示的地方,您正在为命令对象分配连接(这是针对第一个查询)。

当您进入第二个查询时,您将重新定义cmd对象作为新对象,这也删除了之前建立的对连接的任何引用。

尝试使用第二段代码:

strQuery = "INSERT INTO [SD_EPOS_Entry]" _
    & " ([Trade_Activity_Code] " _
    & " VALUES " _
    & " (@Trade_Activity_Code1)"

cmd = New SqlCommand(strQuery, cnn) 'Define the connection to be used for the command.