在最后一个插入操作中捕获多行并在不使用触发器的情况下从中进行选择?

时间:2015-07-27 19:44:41

标签: sql sql-server tsql

我有以下插入操作:

declare @appName varchar(35), @modName varchar(125), @cnt int;
select @cnt=0;
BEGIN TRY
    insert into dbo.AppsMonitor (
        AppName, AppLoadTime, AppLastUpdate, ModName, ModLoadTime, ModLastUpdate , ModErrMsg
    )
    SELECT
        _Scanner.value('@scannerName'   ,   'varchar(25)') AS scannerName
        , _Scanner.value('@StartAt' ,   'varchar(22)') AS LoadTime
        , _Scanner.value('@LastUpdate'  ,   'varchar(22)') AS LastUpdate

        , _Module.value('@modName'  ,   'varchar(125)') AS ModName
        , _Module.value('@StartAt'  ,   'varchar(22)') AS LoadTime
        , _Module.value('@LastUpdate'   ,   'varchar(22)') AS LastUpdate

        , _Module.value('ErrMsg[1]' ,   'varchar(500)') AS ErrMsg
    FROM @xml.nodes('/AllMyScanners/Scanners/Scanner') 
                        As AllMyScanners(_Scanner)  
    CROSS APPLY _Scanner.nodes('Modules/Module') 
                        AS Modules(_Module)
    select @cnt=@@ROWCOUNT
END TRY
BEGIN CATCH
    set @rr=-2;
    print 'Err#4'
END CATCH

我想从插入的缓冲区中选择一些字段(类似@@ inserted),我刚刚插入到dbo.AppsMonitor表中进行分析。

如何在不使用触发器的情况下执行此操作?我的团队不允许使用触发器!

2 个答案:

答案 0 :(得分:3)

您可以使用OUTPUT Clause执行此操作。使用OUTPUT INSERTED.xxx

答案 1 :(得分:0)

谢谢你的回答。为了让其他读者更清楚,使用OUTPUT for INSERTED的代码是

BEGIN TRY
    insert into dbo.AppsMonitor (
        AppName, AppLoadTime, AppLastUpdate, ModName, ModLoadTime, ModLastUpdate , ModErrMsg
    )
    OUTPUT INSERTED.AppName, INSERTED.ModName into @tmpVar 
    SELECT
        _Scanner.value('@scannerName'   ,   'varchar(25)') AS scannerName
        , _Scanner.value('@StartAt' ,   'varchar(22)') AS LoadTime
        , _Scanner.value('@LastUpdate'  ,   'varchar(22)') AS LastUpdate

        , _Module.value('@modName'  ,   'varchar(125)') AS ModName
        , _Module.value('@StartAt'  ,   'varchar(22)') AS LoadTime
        , _Module.value('@LastUpdate'   ,   'varchar(22)') AS LastUpdate

        , _Module.value('ErrMsg[1]' ,   'varchar(500)') AS ErrMsg
    FROM @xml.nodes('/AllMyScanners/Scanners/Scanner') 
                        As AllMyScanners(_Scanner)  
    CROSS APPLY _Scanner.nodes('Modules/Module') 
                        AS Modules(_Module)
    select @cnt=@@ROWCOUNT

END TRY
BEGIN CATCH
    set @rr=-2;
    print 'Err#4'
END CATCH