1

问题已更新,请参阅本文结尾:

我有两个表需要从中存档数据。第一个是存储客户、供应商、商店和发票编号的 INVOICE 表。第二个是 INVOICE LINE ITEM 表,其中存储供应商/发票编号,以及行项目编号和特定项目信息。换句话说,INVOICE 表将发票与客户/供应商联系起来,而 INVOICE LINE ITEM 表将项目与该特定发票联系起来。

目标是归档这些表中超过 2 年的所有数据。问题是 INVOICE LINE ITEM 表上没有日期,只有 INVOICE 表。这是我到目前为止所拥有的:

IF @CutOffDate IS NULL 
BEGIN
    SET @CutOffDate = DATEADD(mm, -24, CURRENT_TIMESTAMP)

END
ELSE
BEGIN
    IF @CutOffDate > DATEADD(mm, -24, CURRENT_TIMESTAMP)
    BEGIN
        RAISERROR ('Cannot delete data from last 24 months', 16, 1)
        RETURN -1
    END
END

BEGIN TRAN


    INSERT INTO archive.INVOICE
            SELECT *
            FROM INVOICE
    WHERE invoice_date < @CutOffDate

    IF @@ERROR <> 0
    BEGIN
        ROLLBACK TRAN
        RAISERROR ('Error occured while moving data from INVOICE', 16, 1)
        RETURN -1
    END

    INSERT INTO archive.INVOICE_LINE_ITEM
            SELECT *
            FROM INVOICE_LINE_ITEM
    WHERE invoice=
        (Select invoice
        From INVOICE
        WHERE invoice_date < @CutOffDate
        )

  IF @@TRANCOUNT > 0
    BEGIN
        COMMIT TRAN
        RETURN 0
    END

END

问题是,每当我尝试执行它时都会收到此错误:

Msg 208, Level 16, State 1, Procedure ArchiveData, Line 26
Invalid object name 'archive.INVOICE'.
Msg 266, Level 16, State 2, Procedure ArchiveData, Line 26
Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 0, current count = 1.

但我知道archive.INVOICE 确实存在(我现在正在查看)。这几天一直在纠结这个问题,求大神帮忙!如果您需要更多信息,请告诉我!

编辑:

谢谢 Demo,原来第一个错误是因为另一个数据库在一个单独的模式中而发生的。太傻了,我没有注意到。

但是,现在第一部分可以工作了,但是当我看到这段代码时遇到了一个问题:

INSERT INTO argus_archive.argus.INVOICE_LINE_ITEM
        SELECT *
        FROM argus.INVOICE_LINE_ITEM
        WHERE invoice=
            (Select invoice
            From argus.INVOICE
            WHERE invoice_date < @CutOffDate
            )

目标是归档与刚刚归档的 Invoices 对应的所有行,但由于每个 Invoice 在 Line Items 表中都有多行,因此出现此错误:

Msg 512, Level 16, State 1, Procedure ArchiveData, Line 38
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
4

1 回答 1

1

就像错误消息所暗示的那样,您的子查询返回多个值,并且无法使用=.

相反,我会建议 a JOIN,并添加 aDISTINCT以匹配预期的原始功能:

INSERT INTO argus_archive.argus.INVOICE_LINE_ITEM
SELECT DISTINCT ilt.*
FROM 
    argus.INVOICE_LINE_ITEM ilt
    JOIN argus.INVOICE i
        ON i.invoice = ilt.invoice 
        AND i.invoice_date < @CutOffDate

编辑:

删除:

DELETE ilt
FROM 
    argus.INVOICE_LINE_ITEM ilt
    JOIN argus.INVOICE i
        ON i.invoice = ilt.invoice 
        AND i.invoice_date < @CutOffDate
于 2012-11-19T18:11:38.333 回答