简体   繁体   中英

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..

使用您的方法\\逻辑

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM