条件比较两个日期从参数和ADD,如果它满足

时间:2016-11-10 10:39:57

标签: sql-server sql-server-2008 stored-procedures sql-server-2012 procedure

这是我的程序,我在程序中日期 我必须检查FROM和TO日期之间的差异是否大于2

如果条件满足,我必须在几天内添加2天并将其设置为TODATE

ALTER PROCEDURE [dbo].[sp_TU_AvgStdDev_Report] 
@FromDate as Datetime,
@ToDate as Datetime,
@RecipeCode as Varchar(8000),
@Grade as Varchar(10),
@WcID as Int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT ON;
IF (condition to check if @FromDate - @ToDate  > 2)
--if it satisfies
SET @ToDate to @fromDate+2Days

请帮我搞清楚......

4 个答案:

答案 0 :(得分:2)

您需要使用日期函数。

ALTER PROCEDURE [dbo].[sp_TU_AvgStdDev_Report] 
@FromDate as Datetime,
@ToDate as Datetime,
@RecipeCode as Varchar(8000),
@Grade as Varchar(10),
@WcID as Int
AS
BEGIN
IF (datediff(day,@FromDate,@ToDate)>2)
SET @ToDate =  DATEADD(day,2, @fromDate)

答案 1 :(得分:1)

使用DATEDIFFDATEADD功能

IF DATEDIFF(D,@FromDate,@ToDate)  > 2
BEGIN  
  --if it satisfies
  SET @ToDate = DATEADD(D,2, @fromDate)
END

答案 2 :(得分:1)

首先将日期部分从日期中删除,将其转换为日期,如

 convert(date,convert(varchar,@FromDate))
 convert(date,convert(varchar,@ToDate))

那么你将只有日期,然后你可以使用DATEDIFF sql函数找到两个日期之间的区别

最终解决方案

IF DATEDIFF(day,convert(date,convert(varchar,@FromDate)),convert(date,convert(varchar,@ToDate)))  > 2
BEGIN  
  --if it satisfies
  SET @ToDate = DATEADD(day,2, convert(date,convert(varchar,@FromDate)))
END

答案 3 :(得分:1)

您必须使用DateDiff 使用以下查询可能会对您有所帮助。

if( Datediff(day, Todate, FromDate) > 2)
// Your query