我是 SQL 新手。我有一個我想解決的問題。
我想復制現有表中的行 - 同一“報告”表中的“報告”,用于從上一個財政年度(例如 2021 年)到新財政年度(例如 2022 年)仍未完成的任務。
如果“TaskACompletedDate”和“TaskBCompletedDate”未完成,它將保持未完成狀態并從“2021”財政年度結轉到“2022”財政年度。
我們將需要檢查從財政年度“2021”到“2022”的未結專案的用戶,以確保沒有重復。
如果未完成的專案已經翻轉,則檢查“TaskADueDate”和“TaskBDueDate”是否有更新,并相應地更新更改。

我的代碼如下。但它沒有按預期作業。
/* Code for table creation */
IF NOT EXISTS (
select * from sysobjects where name='Report' and xtype='U')
CREATE TABLE Report (
[ReportId] INT,
[TaskADueDate] DATETIME,
[TaskACompletedDate] DATETIME,
[TaskBDueDate] DATETIME,
[TaskBCompletedDate] DATETIME,
[FinancialYear] INT
);
INSERT INTO Report VALUES
(1,'2021-12-12 00:00:00','2021-12-12 00:00:00','2021-12-31
00:00:00','2021-12-31 00:00:00',2021),
(2,'2021-12-13 00:00:00',NULL,'2022-01-01 00:00:00',NULL,2021),
(3,'2022-02-01 00:00:00',NULL,'2022-03-02 00:00:00',NULL,2021),
(4,'2022-02-02 00:00:00',NULL,'2022-03-03 00:00:00',NULL,2021);
/* Code for Roll Over to next financial year */
DECLARE @FinancialYearFrom int,
DECLARE @FinancialYearTo int
SET @FinancialYearFrom = 2021
SET @FinancialYearTo = 2022
/*View Outstanding Tasks in FY2021*/
SELECT * FROM REPORT TABLE
WHERE FinancialYear = @FinancialYearFrom AND TaskACompletedDate IS NULL AND TasKBCompletedDate IS NULL
/*Check rows to ensure that the rows in ReportID 2,3,4 is not carried forward to FY2022.
If copied over, just update DueDate if there is any changes.*/
IF(SELECT COUNT(*) FROM Report WHERE FinancialYear = @FinancialYearTo) <> 0
Update Report SET
TaskADueDate = NewTaskADueDate
TaskBDueDate = NewTaskBDueDate
ELSE
INSERT INTO Report (TaskADueDate, TaskACompletedDate, TaskBDueDate, TaskBCompletedDate, FinancialYear)
VALUES (SELECT TOP (1) [TaskADueDate] FROM Report WHERE FinancialYear = @FinancialYearFrom,
SELECT TOP (1) [TaskACompletedDate] FROM Report WHERE FinancialYear = @FinancialYearFrom,
SELECT TOP (1) [TaskBDueDate] FROM Report WHERE FinancialYear = @FinancialYearFrom,
SELECT TOP (1) [TaskBDueDate] FROM Report WHERE FinancialYear = @FinancialYearFrom,
@FinancialYearTo)
uj5u.com熱心網友回復:
例如,我只是將 10 添加到您的 ReportId 以創建新行,因為您沒有在架構中使用任何型別的 auto_increment。只需根據需要將固定年份替換為引數即可。
小提琴
INSERT INTO Report
SELECT ReportId 10
, TaskADueDate, TaskACompletedDate
, TaskBDueDate, TaskBCompletedDate
, FinancialYear 1
FROM Report
WHERE FinancialYear = 2021
AND (TaskBCompletedDate IS NULL AND TaskACompletedDate IS NULL)
;
UPDATE注意:如果不參考原始行或允許加入行的附加鍵(每年唯一),則無法執行您的邏輯。如果要根據先前的“相關”行更新現有行,請將該詳細資訊添加到設計和問題中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438779.html
標籤:sql
