SQL 如何将日期时间字段添加到 + 1 天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15207811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add datetime Field to + 1 day
提问by user937194
In My stored procedure I have a StartDate and EndDate fields are in Varchar(10)
在我的存储过程中,我有一个 StartDate 和 EndDate 字段在 Varchar(10) 中
@StartDate Varchar(10),
@EndDate Varchar(10)
I am giving an input from the UI for start date 03/01/2013 and 03/04/2013
我正在从 UI 输入开始日期 03/01/2013 和 03/04/2013
For end date I need to Add one day + that is if my EndDate is 03/04/2013 I need to Update that to 03/05/2013..
对于结束日期,我需要添加一天 + 即如果我的 EndDate 是 03/04/2013,我需要将其更新为 03/05/2013..
Thanks
谢谢
回答by Kaf
If this is a new stored procedure (or not any other codes using it), best thing is to change your variables to Date type. Because if you comparing data by date
you should compareDates not varchar values
.
如果这是一个新的存储过程(或没有任何其他代码使用它),最好的办法是将您的变量更改为 Date 类型。因为if you comparing data by date
你应该比较Dates not varchar values
。
If you CAN
change the variable type then you can add a day using DATEADD()
function as below.
如果CAN
更改变量类型,则可以使用DATEADD()
如下函数添加一天。
--if @enddate is a date type
select @enddate = dateadd(day,1,@enddate)
If you CANNOT
change variable types, you better pass them in ISO format
(ie; yyyymmdd
) because your current string format is culture specific and query could fail in a server with a different culture.
如果您CANNOT
更改变量类型,最好将它们传入ISO format
(ie; yyyymmdd
),因为您当前的字符串格式是特定于文化的,并且在具有不同文化的服务器中查询可能会失败。
--date pass as yyyymmdd (not culture specific)
select @enddate = convert(varchar(10),
dateadd(day, 1, convert(date, @enddate)), 101)
--date pass as mm/dd/yyyy (US culture)
select @enddate = convert(varchar(10),
dateadd(day, 1, convert(date, @enddate,101)), 101)
回答by Jeff Rosenberg
SET @EndDate = DATEADD (d, 1, CAST(@StartDate AS datetime))
gives you the answer as a datetime
. You can then convert back to a varchar if you need:
SET @EndDate = DATEADD (d, 1, CAST(@StartDate AS datetime))
给你一个答案datetime
。如果需要,您可以然后转换回 varchar:
SET @EndDate = CAST(DATEADD (d, 1, CAST(@StartDate AS datetime)) AS varchar(10))
SET @EndDate = CAST(DATEADD (d, 1, CAST(@StartDate AS datetime)) AS varchar(10))