-1

This is my query:

SELECT DISTINCT
    'wk ' + TRIM(CONVERT(varchar(max), DATEADD(Week, DATEDIFF(week, 0, CONVERT(VARCHAR(max), period)), -1))) [week]
FROM    
    ABC
GROUP BY 
    TRIM(CONVERT(varchar(max), DATEADD(Week, DATEDIFF(week, 0, CONVERT(VARCHAR(max), period)), -1)))

I get a result like this: wk Aug 7 2022 12:00AM

But I want this format wk Aug 7, 2022

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Use `varchar(14)` instead of varchar max. – Dale K Sep 10 '22 at 08:12
  • how do i add the (,) in between the date and year – talent in making Sep 10 '22 at 08:22
  • 2
    Just change your outer `max` to 14. – Dale K Sep 10 '22 at 08:22
  • 5
    Never use `varchar(max)` unless you know you are dealing with 8+mb strings - unlikely with dates; You probably don't need to cast your *period* column at all, and what do you think *group by* is doing for you here, given you're selecting *distinct* values? – Stu Sep 10 '22 at 08:28
  • @Stu i got your point, thanks but how do i add the comma(,) in between wk Aug 7 and 2022 ? do you have any idea ? – talent in making Sep 10 '22 at 08:41
  • 1
    Honestly, it seems like you should be passing the `date` to the application layer, and then controlling the *format* in the presentation layer. – Thom A Sep 10 '22 at 09:22

1 Answers1

2

There was an error in the answer, it always returned january, the error is fixed now

You could build your string using the datepart function

declare @period datetime = '20220807' -- getdate()

SELECT 'wk ' + 
       left(datename(month, @period), 3) + 
       ' ' + convert(varchar(2), datepart(day, @period)) + 
       ' ,' + convert(varchar(4), datepart(year, @period))

looks like this wk Aug 7 ,2022

To convert your select clause to use this,

declare @table1 table (id int, period date)
insert into @table1 (id, period) values (1, '20220807'), (2, '20211130')

SELECT 'wk ' + 
       left(datename(month, dateadd( week, DATEDIFF( week, 0, CONVERT(VARCHAR(12), convert(date, period))), -1)), 3) + 
       ' ' + convert(varchar(2), datepart(day, dateadd( week, DATEDIFF( week, 0, CONVERT(VARCHAR(12), convert(date, period))), -1))) + 
       ' ,' + convert(varchar(4), datepart(year, dateadd( week, DATEDIFF( week, 0, CONVERT(VARCHAR(12), convert(date, period))), -1)))
from   @table1

it looks like this

COLUMN1
wk Aug 7 ,2022
wk Nov 28 ,2021
Thom A
  • 88,727
  • 11
  • 45
  • 75
GuidoG
  • 11,359
  • 6
  • 44
  • 79