-1

'UNK-JAN-2015' This is my date value. UNK refers Unknown value. Now I need to get only month from that. Is there any way to find it......

Jasper
  • 41
  • 2
  • 5

5 Answers5

3
SELECT 
RIGHT(DateString, 4) [Year], 
LEFT(RIGHT(DateString, 8), 3) [Month] 
FROM YourTable
SouravA
  • 5,147
  • 2
  • 24
  • 49
1

Using SUBSTRING

Query

SELECT SUBSTRING('UNK-JAN-2015',LEN('UNK-JAN-2015')-3,4);

Using RIGHT

Query

SELECT RIGHT('UNK-JAN-2015', 4);

To get Month from the given string,

Query

SELECT SUBSTRING('UNK-JAN-2015',5,3) AS [Month];
Ullas
  • 11,450
  • 4
  • 33
  • 50
  • please view the edit to the post and update accordingly, as the OP s now requesting the month – Tanner Mar 10 '15 at 11:35
0

If you instead want to find the last token separated by - you could use this:

SELECT DT = REVERSE(SUBSTRING(REVERSE(@DateString),0,CHARINDEX('-',REVERSE(@DateString)))) 

This also returns 2015, so the text behind the last dash. So it does not only return the last 4 characters. With UNK-JAN-2015/02/09 it returns 2015/02/09.

Edit: If you want the middle part, the month, you could use:

SELECT SUBSTRING(@DateString, CHARINDEX('-',@DateString)+1,LEN(@DateString)-CHARINDEX('-',@DateString,CHARINDEX('-',@DateString))-(CHARINDEX('-',@DateString)+1)) 
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Query

declare @text varchar(100)
set @text='UNK-JAN-2015'

set @text= '<r>'+ REPLACE(@text,'-','</r><r>') + '</r>'

select i.value('r[2]','varchar(10)') AS Year 
from (select cast(@text as xml) xml)out CROSS APPLY out.xml.nodes('/') x(i) 
Ullas
  • 11,450
  • 4
  • 33
  • 50
Vindhyachal Kumar
  • 1,713
  • 2
  • 23
  • 27
0

To get an actual month value, rather than simply taking the 3 characters that make up the month portion of the string, you can convert it to a date using some string manipulation and extract the month from it:

DECLARE @val NVARCHAR(15) = 'UNK-JAN-2015'

SELECT  CONVERT(DATETIME, RIGHT(@val, 4) + '-' + SUBSTRING(@val, 5, 3)) AS TheDate,
    MONTH(CONVERT(DATETIME, RIGHT(@val, 4) + '-' + SUBSTRING(@val, 5, 3))) MonthNumber,
    DATENAME(MONTH,
           CONVERT(DATETIME, RIGHT(@val, 4) + '-' + SUBSTRING(@val, 5, 3))) [MonthName]

Output:

TheDate                   MonthNumber   MonthName
2015-01-01 00:00:00.000   1             January

This assumes that the value is always in the same format: XXX-MMM-YYYY (where XXX is some prefix)

Tanner
  • 22,205
  • 9
  • 65
  • 83