Pergunta

In my SQL Server database I have the dates stored as char(12) in the following format:

yyyymmddhhmm

I didn't create the definition and I cannot modify it. I always dealt with this string at application level, by using C#.

Now I need to perform a task in TSQL and I need to group by month. Therefore I need to extract the month. Is there any TSQL function available for this task?

In case there is not, is it a good solution to create a stored procedure, getMonth(stringDate) that takes the string and extract the 4th and 5th characters from it? Can I use the clause:

group by getMonth(stringDate)

in my query? Thanks

Foi útil?

Solução

You can use the following to get your month, since month is always 2 characters after the 4 character year.

declare @date char(12)
set @date = '201203220906'
select substring(@date, 5, 2)

results: 03

or another way to get it is, then you can group by the results in either query:

declare @date char(12)
set @date = '201203220906'
select Month(cast(left(@date, 8) as datetime))

Outras dicas

You can;

SUBSTRING(fld, 5, 2)

Personally I would not create a UDF for something so simple (which is what you would consider rather than an SP) unless you find yourself needing to cast that string to DATETIMEs

Assuming

CREATE TABLE #Table(
    DateValue char(12),
    Value int)

INSERT INTO #Table VALUES ('20120110833', 1)
INSERT INTO #Table VALUES ('20120110833', 2)
INSERT INTO #Table VALUES ('20120110833', 3)
INSERT INTO #Table VALUES ('20120210833', 4)
INSERT INTO #Table VALUES ('20120210833', 5)

You can simply do this:

select 
    MONTH(CAST(LEFT(DateValue, 8) as datetime)) Month, 
    SUM(value)
FROM
    #Table
GROUP BY
    MONTH(CAST(LEFT(DateValue, 8) as datetime))

trim the hour/minute part, cast as datetime and apply MONTH function

For this specific case (date in char type with format yyyymmddhhmm), you can use in your query the next functions:

substring (to extract yyyymmdd), convert (to get datetime value), datepart (to get month component)

...then you can group by month (or whatever date component), change datecolumnname and tablename with appropiate values

select datepart(month,convert(datetime,substring(datecolumnname,1,8),112)), 
   count(datepart(month,convert(datetime,substring(datecolumnname,1,8),112))) 
from tablename 
   group by datepart(month,convert(datetime,substring(datecolumnname,1,8),112))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top