开发者

How to get year and month separately from this string in sql server?

开发者 https://www.devze.com 2023-02-02 21:59 出处:网络
开发者_StackOverflow中文版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 h
开发者_StackOverflow中文版

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

0

精彩评论

暂无评论...
验证码 换一张
取 消