如何在SQL Server 2012中的select语句中添加月份字段?

时间:2014-08-07 09:01:10

标签: sql sql-server sql-scripts

我的代码是:

create table t_AccountTransactions
(
    CompanyID varchar(50) ,
    RecordID int ,
    Branch varchar(100) ,
    Year int,
    Month varchar(2),
    Date_Gregorian date,
    Date_Persian varchar(100),
    VoucherType varchar(100),
    VoucherNumber varchar(100),
    Row varchar(100),
    AccountNumber_SL varchar(100),
    AccountNumber_DL varchar(100)
)

insert into t_AccountTransactions (RecordID, CompanyID, Branch, Year, Month, Date_Gregorian, Date_Persian, VoucherType, VoucherNumber, Row, AccountNumber_SL, AccountNumber_DL)
   select 
      item.VchItmId, @CompanyID, hdr.BranchCode, hdr.Year,
      right('0' + DATEPART(month,hdr.Month),2),  
      hdr.VchDate, 'Date_Persian', Vtype.Title, hdr.Num,
      item.Seq, item.SLRef, item.DLRef
   from 
      SgDb1_dat.ACC.AccVchHdr as hdr, SgDb1_dat.ACC.AccVchItm as item, SgDb1_dat.ACC.AccVchType as Vtype
   where 
      hdr.HdrVchID = item.HdrRef 
      and hdr.Ctgry = vtype.Code

在我的表月中将显示为1,2,3,4,...我想将其修改为显示为01,02,03和...

请帮助我如何为此目的修改我的选择语句。

谢谢。

1 个答案:

答案 0 :(得分:0)

你可以这样:

 select case when DATEPART(month,getdate())<10
        then '0'+DATEPART(month,getdate())
        else DATEPART(month,getdate())
 end

您完成的代码将是:

insert into t_AccountTransactions (RecordID,CompanyID,Branch,Year,Month,Date_Gregorian,Date_Persian,VoucherType,VoucherNumber,Row,AccountNumber_SL,AccountNumber_DL)
select item.VchItmId,@CompanyID,hdr.BranchCode,hdr.Year,
case when DATEPART(month,hdr.Month)<10 then '0'+DATEPART(month,hdr.Month) else DATEPART(month,hdr.Month) end ,hdr.VchDate,'Date_Persian',Vtype.Title,hdr.Num,item.Seq,item.SLRef,item.DLRef
        from SgDb1_dat.ACC.AccVchHdr as hdr , SgDb1_dat.ACC.AccVchItm as item , SgDb1_dat.ACC.AccVchType as Vtype
            where hdr.HdrVchID=item.HdrRef and hdr.Ctgry = vtype.Code

更新:

将案例部分更改为:

case when DATEPART(month,hdr.Month)<10 then '0'+CAST(DATEPART(month,hdr.Month) as varchar) else    CAST(DATEPART(month,hdr.Month) as varchar) end 

请记住,在case语句中,所有结果都应该具有相同的类型。