简体   繁体   中英

How can I concatenate two dates as strings in Sql

I have a date field and i need to display the week of the date field in select statement,

Eg : if the date is '2014-09-15 00:00:00', i need to display as '2014-09-14 to 2014-09-20 ' which is start day to end day of the week

I have tried using

   Select dateadd(week, datediff(week, 0, getdate()), -1)+' to ' +DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7) 

But it is giving me conversion failure,how can i write the above to display in sql

Both of these expressions

dateadd(week, datediff(week, 0, getdate()), -1)

and

DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7)

returns a Datetime value and ' to ' is a string value.

You will need to convert your datetime values to a string to concatenate these values together.

SELECT CONVERT(VARCHAR(23), dateadd(week, datediff(week, 0, getdate()), -1), 121) 
       + ' to ' +
     CONVERT(VARCHAR(23), DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7), 121)

RESULT:  2014-09-14 00:00:00.000 to 2014-09-21 00:00:00.000

你必须像这样投下你的陈述

SELECT CONVERT(VARCHAR(10), dateadd(week, datediff(week, 0, getdate()), -1), 25) + ' to ' + CONVERT(VARCHAR(10), DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7), 25)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM