批量复制后触发器根本不会触发

时间:2017-08-20 07:31:17

标签: sql-server tsql sql-server-2012 triggers

我想在使用bulkcopy将插入的记录插入数据库后更新插入的记录。我想在插入后写了一个触发器来为我做更新。如果我一个接一个地插入记录但是在批量复制插入后拒绝工作,则触发器工作正常。

我已将火灾触发器(SqlBulkCopyOptions.FireTriggers& SqlBulkCopyOptions.CheckConstraints)添加到连接,但它仍然无效。

这是我写的触发器:

CREATE TRIGGER [dbo].[Trigger_assessment]
ON [dbo].[assessment]
AFTER INSERT 
AS
BEGIN
    SET NoCount ON

    Declare @a as int
    Declare @b as int

    SELECT @b = exam_score, @a = ca 
    FROM inserted

    UPDATE assessment 
    SET final_ca = ca*0.3, final_exam = exam_score * 0.7,
        f_score = ((ca * 0.3) + (exam_score * 0.7)) 
    WHERE exam_score = @b AND ca = @a
END

以及批量副本:

     Dim koneksi_excel As New      System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & path1.Text & " '; Extended Properties=""Excel 12.0 xml;HDR=yes""")

    koneksi_excel.Open()
    Dim query_excel As String = "select * from [Sheet1$]"

    Dim cmd As OleDbCommand = New OleDbCommand(query_excel, koneksi_excel)

    Dim rd As OleDbDataReader

    Dim koneksi As New SqlConnection()

    If mysqlconnectionstring.State = ConnectionState.Closed Then
        mysqlconnectionstring.Open()
    End If
    Using BulkCopy As SqlBulkCopy = New SqlBulkCopy(ConfigurationManager.ConnectionStrings("SchoolDBConnectionString").ConnectionString.ToString, SqlBulkCopyOptions.FireTriggers & SqlBulkCopyOptions.CheckConstraints)

        BulkCopy.DestinationTableName = "dbo.assessment"

        Try

            rd = cmd.ExecuteReader
            BulkCopy.WriteToServer(rd)
            rd.Close()
            mysqlconnectionstring.Close()
            MsgBox("Data import succesful", MsgBoxStyle.Information, "imports")
            path.Text = ""
        Catch ex As Exception
            MsgBox(ex.ToString)
        Finally
            mysqlconnectionstring.Close()
        End Try
    End Using

我想要帮助,谢谢,

1 个答案:

答案 0 :(得分:2)

inserted虚拟表是一个表,因此可以有多个行。如果进行批量插入(或更新),则此表中将包含多行。你需要考虑到这一点。您可以在此处详细了解:Use the inserted and deleted Tables

您的更正触发器将是:

CREATE TRIGGER [dbo].[Trigger_assessment]
ON [dbo].[assessment]
after insert
AS
BEGIN
    SET NoCount ON

    update 
        assessment 
    set 
        final_ca=a.ca*0.3,
        final_exam=a.exam_score*0.7,
        f_score=((a.ca*0.3)+(a.exam_score*0.7)) 
    from
        assessment AS a
        inner join inserted as i on
            i.ca=a.ca and
            i.exam_score=a.exam_score;
END