我有一个列[加载日期]的表,我想在SQL Server中添加一列[更新日期] ....

时间:2016-04-11 18:41:31

标签: sql-server-2012

我有一个包含[Load date]列的表格,我希望添加一个列[Updated Date],其中Mon-Fri数据与[Load Date]相同,但是Sun-Sat作为{{1的Mon数据我怎么能在SQL Server中做到这一点?

1 个答案:

答案 0 :(得分:0)

CREATE TABLE table3
( 
 orderdate datetime
)


CREATE FUNCTION dbo.getupdateddate(@orderdate datetime)
RETURNS datetime
AS
BEGIN
declare @updateddate datetime
  if datepart(weekday,@orderdate) in (1,2,3,4,5)
  set @updateddate=@orderdate;
  else 
  select top 1 @updateddate= orderdate from table3 
where datepart     (weekday,@orderdate) =2
  order by orderdate desc 
  return @updateddate

END

ALTER TABLE table3
ADD updateddate AS dbo.getupdateddate(orderdate)

select @@DATEFIRST--7  
insert into table3
(orderdate)
select getdate()

select * from table3  


  orderdate                    updateddate
2016-04-12 00:29:14.343   2016-04-12 00:29:14.343

有几点需要注意:
1.SET DATEFIRST指定一周的第一天。周日美国英语默认为7 2.如果星期一没有天数,你可能想要添加为null