Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

How to split the below integer value in SQL query

Month/Year
012013
022013
122013

I am able to split 122013 as 12 2013 but am not able to split "012013" and "022013" values.

Query i used to split.

SELECT left(ID, 2) as Month , Right(ID, 4) As Years FROM table

Regards,
Abhishek
Posted
Comments
ArunRajendra 8-Apr-14 1:07am    
Can you give the output you are getting when you run your query.

Leading zeros are dropped when you read the number as an integer value. You would need to operate on them as strings (varchar).
 
Share this answer
 
TO split integer values, you need to treat it as a text:
SQL
SELECT LEFT(CONVERT(VARCHAR(10),ID), 2) as Month , RIGHT(CONVERT(VARCHAR(10),ID), 4) As Years
FROM table
 
Share this answer
 
Yes, when I took the column as Varchar, it is working fine.

Demo


http://sqlfiddle.com/#!6/2d445/2/0[^]
 
Share this answer
 
Hi All,
Below is the table data

ID
122013
112013
102013
92013
82013
72013
62013
52013
42013
32013
12014

i tried with the below code but its not working

Declare @input int
select @input =ID from @tableVar
IF(COUNT(@INPUT) > 6)
BEGIN
SELECT LEFT(CONVERT(VARCHAR(10),ID), 2) AS MONTH , RIGHT(CONVERT(VARCHAR(10),ID), 4) AS YEARS FROM @TABLEVAR
END
ELSE
BEGIN
SELECT LEFT(CONVERT(VARCHAR(10),ID), 1) AS MONTH , RIGHT(CONVERT(VARCHAR(10),ID), 4) AS YEARS FROM @TABLEVAR
END


Am Getting the output as:

VB
1   2013
1   2013
1   2013
9   2013
8   2013
7   2013
6   2013
5   2013
4   2013
3   2013
1   2014


please suggest me with better answer.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900