开发者

Get year and month from SQL

I want to 开发者_开发百科know how can I get the year and month into my database. For example, suppose it’s August, 2011. The output that I need is like this: CAB 11 08 001 (CAB + YEAR + MONTH + CURRENT NO. in tracking number. )

This is my SQL:

ALTER PROCEDURE [dbo].[generateTrackNo] AS
Declare @tempYear VARCHAR(5),@tempMonth VARCHAR(5)
Set @tempYear = Year(GetDate())
Set @tempMonth = Month(GetDate())
SELECT 'CAB' + Right(Cast(Year(GetDate()) as varchar(10)),2)+ Right(Cast(Month(GetDate()) as varchar(10)),2) + Right('000000'+ Cast(CurrentNo as varchar(10)), 5) from tblTrackNo where GenYear = @tempYear
--UPDATE tblTrackNo SET CurrentNo = CurrentNo + 1 where GenYear = @tempYear

The output for this is CAB1180035, but I need CAB1108035. I need to put zero(0) 08 like this for the month.

In my table I have only genYear and Current No. Do I need to add another column for MONTH?


It looks like you're making separate columns for YEAR, MONTH, etc.

Most (all?) DBMSs I'm aware of have a Date type. Use it. They put a lot of useful stuff in it, like accepting date inputs in different formats and giving them as output in pretty much any format you can think of.

For example, if you have a DT column of type Date in Oracle, you can output month as

SELECT TO_CHAR(DT, "MM") FROM MYTABLE;

and the month will always be displayed as 2 digits (01, 02, ... 12)


SELECT 
    'CAB'
    + RIGHT(YEAR(GetDate()),2)
    + RIGHT('0' + CONVERT(VARCHAR, MONTH(GetDate())),2)
    + Right('00000' + Cast(CurrentNo as varchar(10)), 5)

That might work..


Using your method \ logic..

Right('0' + Cast(Month(GetDate()) as varchar(10)),2)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜