How to concatenate declare date variables

1069 views sql
6

How do I concatenate declare date variables so they are in one column? I need to show the dates as between dates. When I run the following I get an error message.

Declare @startdate date  = '20180101'
Declare @enddate   date  = '20180731'
SELECT
  'Dates'       =   @startdate+' - '+@enddate
FROM TABLE

Error Message:

The data types date and varchar are incompatible in the add operator.

answered question

2 Answers

7

Convert them to strings before concatenating them. For the default format on your system:

select dates = convert(varchar(255), @startdate) + ' - ' + convert(varchar(255), @enddate)

To specifically convert to YYYYMMDD use format 112:

select dates = convert(varchar(255), @startdate, 112) + ' - ' + convert(varchar(255), @enddate, 112)

posted this
2

You can use concat() :

SELECT CONCAT(@startdate, ' - ', @enddate) AS Dates
FROM TABLE;

posted this

Have an answer?

JD

Please login first before posting an answer.