我有表T1:
Id Invoice Date
1 A100
2 B100
我想用ID为基础的递增日期更新表T1
所需结果:
Id Invoice Date
1 A100 GetDate()
2 B100 GetDate()+1
是否有可用的东西像这样
:update T1
set [Date]= GetDate() + ROW_NUMBER() over (order by id)
from T1
答案 0 :(得分:3)
使用与Larnu类似但更直接的方法,您可以直接更新CTE:
WITH cte AS
(
SELECT *
, ROW_NUMBER() over (order by id) rn
FROM T1
)
UPDATE cte
SET [date] = DATEADD(DAY, rn, GETDATE())
答案 1 :(得分:1)
这是您要寻找的东西吗?根据ID
更新日期列 update T1
set [Date]= GetDate() + (id-1)
from T1
答案 2 :(得分:1)
使用dateadd
update T2
SET T2.D=dateadd(dd,T3.rn,getdate())
FROM
T1 as t2 INNER JOIN
(
select *,ROW_NUMBER() over (order by [id]) as rn from T1
) T3 ON t2.id=t3.id
答案 3 :(得分:1)
一种方法是使用CTE使用ROW_NUMBER
和DATEADD
评估新日期,然后使用CTE中的值UPDATE
评估新日期:
USE Sandbox;
GO
CREATE TABLE TestTable (ID int IDENTITY, SomeDate date)
INSERT INTO dbo.TestTable (SomeDate)
VALUES (GETDATE()),(GETDATE()),(GETDATE()),(GETDATE()),(GETDATE());
GO
SELECT *
FROM TestTable;
GO
WITH NewDates AS(
SELECT ID, DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY TT.ID), GETDATE()) AS NewDate
FROM dbo.TestTable TT)
UPDATE TT
SET SomeDate = ND.NewDate
FROM dbo.TestTable TT
JOIN NewDates ND ON TT.ID = ND.ID;
GO
SELECT *
FROM TestTable;
GO
DROP TABLE TestTable;
GO
答案 4 :(得分:0)
使用recursive cte
生成Id
和dates
,然后根据join
列Id
来更新表中的数据
with cte as (
select 1 AS Id, getdate() as dt
union all
select cte.Id+1, dateadd(d,1,cte.dt)
from cte
where cte.Id < (SELECT MAX(ID) FROM T1)
)
UPDATE T1
SET T1.Date = cte.dt
FROM T1 INNER JOIN cte ON T1.Id = cte.Id
答案 5 :(得分:0)
您不能直接在更新查询中使用Windowed functions
。您应该将逻辑存储在某些temporary table
中,然后在更新查询中使用该值。一种方法可能如下所示。
;with cte as
(
select id,Invoice,dateadd(DAY, ROW_NUMBER() over (order by id), GetDate()) as dt
from T1
)
update a
set a.[date]= cte.dt
from T1 a join cte on cte.id=a.id
where a.id=cte.id