Code First 迁移 - SQL 使用同一 table 中另一行的数据更新列

Code First Migration - SQL Update column with data from another row in same table

情况:

给定如下table:

Id Price ProductId ValidFrom
1 1,00 1 01-01-01
2 1,00 1 01-01-15
3 1,00 1 01-02-01
4 1,00 2 01-01-01
5 1,00 2 01-01-11
6 1,00 2 01-01-28
7 1,00 2 01-02-01
8 1,00 2 01-01-08

现在我想向 table 添加一个新列“ValidUntil”。因为数据已经存在,所以应该为现有条目预填充新列。

更改后的 table 应如下所示:

Id Price ProductId ValidFrom ValidUntil
1 1,00 1 01-01-01 01-01-15
2 1,00 1 01-01-15 01-02-01
3 1,00 1 01-02-01
4 1,00 2 01-01-01 01-01-11
5 1,00 2 01-01-11 01-01-28
6 1,00 2 01-01-28 01-02-01
7 1,00 2 01-02-01 01-02-08
8 1,00 2 01-02-08

我使用 Entity Framework Core Code First Migration 来更新数据。

问题:

我先重命名该列,然后使用以下行预填充该列:

migrationBuilder.Sql("UPDATE Prices p1 SET p1.ValidUntil = (SELECT TOP 1 ValidFrom FROM Prices p2 WHERE p2.ValidFrom > p1.ValidFrom ORDER BY DATEDIFF(day, p2.ValidFrom, p1.ValidFrom))");

运行更新时出现以下错误:

Incorrect syntax near 'p1'.

Incorrect syntax near ORDER-Keyword.

问题:

我对 SQL 语句的经验较少,因此如果能帮助我理解此语句的错误,我将不胜感激。

此外,如果有人有更适合这种情况的陈述,也欢迎他。

感谢您的帮助。

您可以使用 lead() 获取截止日期:

select p.*,
       lead(validfrom) over (partition by productid order by validfrom) as validuntil
from prices p;

在SQL服务器中,您可以将其合并到update:

with toupdate as (
      select p.*,
             lead(validfrom) over (partition by productid order by validfrom) as new_validuntil
      from prices p
     )
update toupdate
    set validuntil = new_validuntil
    where new_validuntil is not null;