(日期差异查找器)将选择查询的结果传递到if-else循环内的另一个选择查询

时间:2016-03-03 06:55:46

标签: sql sql-server sql-server-2012 date-difference

我正在尝试在表格中查找今天的日期和给定日期之间的日期差异。有些行有1个日期,而其他行有2个日期(采用更早的日期)。我尝试使用动态变量和临时表,但仍无法正常工作

Here is the input table

else
begin
SELECT * INTO #result2
 FROM 
 ( 

  declare @t date
  set @t = '
  select SUBSTRING(Availability, PATINDEX('% [0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]%', [Availability]), 11) as [Date Part] from [ScrappedData_Regina] '

-- extracts date part from a column

  select  distinct [Product Name],[SKU],DATEDIFF(day,cast(@t as date),cast(GETDATE() as date)) as [Delivery Date]  from ScrappedData_Regina
)  -- i want to pass the date part in this select statement

第一个查询将结果为 firstquery result

对于两个日期的情况,我也希望第二次查询的结果相同。

secondquery result

最后将结果合并到一个表

1 个答案:

答案 0 :(得分:0)

我认为你应该能够在一个查询中做到这一点(如果我理解你正在尝试做什么)。删除第一个查询并将第二个查询替换为:

SELECT DISTINCT [Product Name],
                [SKU],
                DATEDIFF(DAY, CAST(
                    SUBSTRING(Availability,
                        PATINDEX('% [0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]%', [Availability]), 11) AS DATE),
                        CAST(GETDATE() AS DATE)
                    ) AS [Delivery Date]
FROM ScrappedData_Regina