Sql-server – TSQL – use columns as date range

sql-server-2008-r2t-sql

Table1

How can I retrieve the cto column using an @variable?

For example, for @Variable = '2019-03-02' the expected output is'MAR 1 - MAR 7'.

Best Answer

It's kind of a barebone question, but...

@DateToUse is the date you are searching for.

@StringOutput is the cto column.

I'm using the ID field as a tie-breaker in order to protect against duplicate or overlapping ranges in from/to fields.

DECLARE @DateToUse DATE
DECLARE @StringOutput VARCHAR(50)

SET @DateToUse = '3/2/2019'

SET @StringOutput = (SELECT TOP (1) cto FROM dbo.MyTable WHERE @DateToUse BETWEEN from AND to ORDER BY ID)

PRINT @StringOutput