Input
@StartDate = '01/25/2010' @EndDate = '0开发者_如何学运维2/06/2010'I have 2 CTEs in a stored procedure as follows:
with CTE_A as
(
[gives output A..Shown below]
),
with CTE_B as
(
Here,
I want to check if @StartDate is NOT in output A then replace it with the last known date. In this case, since @startdate is less than any date in output A hence @StartDate will become 02/01/2010.
Also to check if @EndDate is NOT in output A then replace it with the last known date. In this case, since @enddate is 02/06/2010 hence it will be replace with 02/05/2010.
// Here there is a query using @startDate and @EndDate.
)
output A
Name Date
A 02/01/2010
B 02/01/2010
C 02/05/2010
D 02/10/2010
You don't need a 2nd CTE (untested)
...
SELECT
StartDate, EndDate
FROM
(
SELECT TOP 1
A.Date AS StartDate
FROM
CTEA A
WHERE
A.[Date] >= @StartDate
ORDER BY
A.Date
) Bmin
CROSS JOIN
(
SELECT TOP 1
A.Date AS EndDate
FROM
CTEA A
WHERE
A.[Date] <= @EndDate
ORDER BY
A.Date DESC
) Bmax
You could use MAX/MIN too
精彩评论