简体   繁体   English

嵌套的INSERT,UPDATE,DELETE或MERGE语句在UPDATE中必须具有OUTPUT子句

[英]A nested INSERT, UPDATE, DELETE, or MERGE statement must have an OUTPUT clause in UPDATE

I'm trying to update some values based on every Id in the list. 我正在尝试根据列表中的每个ID更新一些值。 The logic I have seems to be what I want. 我的逻辑似乎就是我想要的。

I want to populate a temporary table of Ids. 我想填充一个Ids临时表。 Then for every ID I want to apply this query and output the deleted date and the ID into a new table I've created. 然后,对于每个我要应用此查询的ID,并将删除的日期和ID输出到我创建的新表中。

I keep getting the error: 我不断收到错误:

Msg 10716, Level 15, State 1, Line 25 A nested INSERT, UPDATE, DELETE, or MERGE statement must have an OUTPUT clause.

What does this mean? 这是什么意思? I thought I am OUTPUTTING into the new table I've created. 我以为我要输出到创建的新表中。

USE datatemp

GO


DECLARE @idlist TABLE (id INT)
INSERT INTO @idlist (id) VALUES (3009099)

DECLARE @EndDate DATETIME
SET @EndDate = '2099-12-12'

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TEMP_TABLE')
BEGIN
    CREATE TABLE  [TEMP_TABLE] (     
        [id] INT,
        [thedatetoend] DATETIME); 
END

BEGIN TRY
    SELECT  *
    FROM @idlist AS idlist
        OUTER APPLY(
                    UPDATE [custprofile]
                    SET thedatetoend = @EndDate
                    OUTPUT idlist.id, DELETED.thedatetoend
                        INTO [TEMP_TABLE]
                    FROM [custprofile] as bc
                    INNER JOIN [custinformation] as cc
                    ON cc.custengageid = bc.custengageid
                    WHERE cc.id = idlist.id
                                    AND bc.modifierid = 2
                                    AND bc.thedatetoend > GETDATE()
                                    AND cc.type = 1) o

I think you may have more success by using a CTE and avoiding the outer apply approach you are currently using. 我认为,通过使用CTE并避免使用当前正在使用的外部应用方法,您可能会获得更大的成功。 Updates made to the CTE cascade to the source table. 对CTE所做的更新级联到源表。 It might look something like the following but as some columns don't reference the table aliases don't expect this to work "as is" (ie I'm not sure if you are outputting ccid or bcid and I don't know which table thedatetoend belongs to.) 它可能看起来像以下内容,但由于某些列未引用表别名,因此不希望它按“原样”运行(即,我不确定您是输出ccid还是bcid,并且我不知道是哪个表thedatetoend所属。)

WITH
      CTE AS (
                  SELECT
                        cc.id AS ccid, bcid AS bcid, thedatetoend
                  FROM [custprofile] AS bc
                  INNER JOIN [custinformation] AS cc ON cc.custengageid = bc.custengageid
                  INNER JOIN @idlist AS idlist ON cc.id = idlist.id
                  WHERE bc.modifierid = 2
                  AND bc.thedatetoend > GETDATE()
                  AND cc.type = 1
            )
UPDATE CTE
SET thedatetoend = @EndDate
OUTPUT ccid, DELETED.thedatetoend
INTO [TEMP_TABLE]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM