问题更新,请看这篇文章的结尾:
我需要两个表来存档数据。第一个是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
)
目标是归档与刚刚归档的发票对应的所有行,但由于每个发票在“行项目”表中有多行,我收到此错误:
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.
答案 0 :(得分:1)
与错误消息建议类似,您的子查询返回多个值,无法使用=
进行比较。
相反,我建议使用JOIN
,并添加DISTINCT
以匹配预期的原始功能:
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