在Output子句中调用存储过程

时间:2013-07-30 17:38:10

标签: sql sql-server tsql

我有一个日历表,我想要获取今天的计划项目并复制记录,保留大部分数据并对某些字段进行一些更改,这样可以正常工作。

问题在于调用存储过程。我需要在另一个表中创建另一个记录并返回范围标识ID。

sp插入从Update获取插入的数据,并使用它来创建新记录,然后返回范围标识。

我尝试使用函数,但不喜欢插入。如何在此声明中调用此sp?

UPDATE calendar_tbl
SET WO=0
OUTPUT 
    inserted.startDate, 
    dateadd(ss, 0, inserted.startDate), 
    inserted.text, 
    inserted.color, 
    inserted.tColor,
    dbo.funcEpoch(inserted.startDate),
    '',
    inserted.id,
    exec dbo.sp_create @AccountNumber,inserted.CompanyID ,inserted.LocationID, inserted.text,inserted.startDate, dateadd(ss, 0, inserted.startDate), inserted.UserID,'',
    inserted.UserID,
    inserted.LocationID,
    inserted.CompanyID,
    inserted.AccountNumber,
    0
    INTO 
        calendar_tbl(
            startDate, 
            endDate,
            text,
            color,
            tColor,
            evLength,
            rtype,
            PID,
            WOID,
            UserID,
            LocationID,
            CompanyID,
            AccountNumber,
            WOorSchedule)
WHERE   
    (SELECT CONVERT(VARCHAR, startDate, 101)) = (SELECT CONVERT(VARCHAR, getdate(), 101)) AND
    accountNumber = @AccountNumber

1 个答案:

答案 0 :(得分:1)

您可以使用可组合DML来嵌套UPDATE,INSERT并捕获auditIds。以下简单示例:

USE tempdb
GO

SET NOCOUNT ON

-- Create a table
IF OBJECT_ID('dbo.sampleTable') IS NOT NULL DROP TABLE dbo.sampleTable
CREATE TABLE dbo.sampleTable ( rowId INT IDENTITY PRIMARY KEY, someData UNIQUEIDENTIFIER DEFAULT NEWID(), dateAdded DATETIME DEFAULT GETDATE(), addedBy VARCHAR(30) DEFAULT SUSER_NAME(), dateModified DATETIME, ts ROWVERSION )
GO
IF OBJECT_ID('dbo.auditTable') IS NOT NULL DROP TABLE dbo.auditTable
CREATE TABLE dbo.auditTable ( auditId INT IDENTITY(1000,1) PRIMARY KEY, rowId INT, someData UNIQUEIDENTIFIER, dateAdded DATETIME, addedBy VARCHAR(30), ts ROWVERSION )
GO

-- Populate table
INSERT INTO dbo.sampleTable DEFAULT VALUES
GO 100


-- Example composable DML query to do both UPDATE, INSERT and record new auditIds
INSERT INTO dbo.auditTable ( rowId, someData, dateAdded, addedBy )
OUTPUT inserted.auditId
SELECT rowId, someData, dateAdded, addedBy
FROM
    (
    UPDATE TOP(10) t1
    SET dateModified = GETDATE()
    OUTPUT inserted.rowId, inserted.someData, inserted.dateAdded, inserted.addedBy
    FROM dbo.sampleTable t1
    WHERE dateModified IS NULL
    ) x


SELECT *
FROM dbo.sampleTable
WHERE dateModified IS NOT NULL

SELECT *
FROM dbo.auditTable

这样的事情对你有用吗?