I have this
WITH sequenced_records AS (
SELECT ROW_NUMBER() OVER (ORDER BY [DateTime] DESC) AS sequence_id, *
FROM StreamView
WHERE TypeOf = @TypeOf
AND [DateTime] >= @DateTime
)
SELECT * FROM sequenced_records WHERE sequence_id = 1;
Which works fine for getting the latest record. But what if it doesn’t find anything? How can I get it to return the latest record going backwards? Meaning if there isnt any newer items than the given DateTime, it would instead go backwards and fetch the first item it find.
thanks
A couple of options:
1)
If @@RowCount = 0perform a separate select.2) Select into a local table, then if that contains no rows, select into it using your new query, then select out of that table for returning data to caller.
And the separate select could be (haven’t tested this and not familiar with with statements, but here goes anyway):
Upon further review, unless you have simplified this query a lot, you are doing too much work: