How to get year and month separately from this string in sql server?
I have this string format mm/yyyy-
01/2010
how do i get the month and year separately from it. I want it separately 01 and 2010 in a way i could compare them?
This should hook you up (assumes that @Date represents your date string):
DECLARE @SlashPos int;
SET @SlashPos = CHARINDEX('/', @Date);
Declare @Month varchar(2);
Declare @Year varchar(4);
SET @Month = SUBSTRING(@Date, 1, @SlashPos - 1);
Set @Year = SUBSTRING(@Date, @SlashPos + 1, LEN(@Date) - @SlashPos);
At this point, @Month
and @Year
will contain strings representing the month and year.
Example:
declare @d char(7);
declare @Month varchar(2);
declare @Year varchar(4);
set @d = '01/2010';
SET @Month = LEFT(@d, 2);
SET @Year = RIGHT(@d, 4);
check out help for substring and charindex functions
精彩评论