日期:2014-05-18  浏览次数:20530 次

ms-sql 2000 怎么取上个月的月份
我想建一个表:

if   exists   (select   *   from   dbo.sysobjects   where   id   =   object_id(N '[dbo].[aa] ')   and   OBJECTPROPERTY(id,   N 'IsUserTable ')   =   1)
drop   table   [dbo].[aa]


go


CREATE   TABLE   [dbo].[aa]   (
[市名]   [nvarchar]   (50)   COLLATE   Chinese_PRC_CI_AS   NOT   NULL
[钱数]   [nvarchar]   (50)   COLLATE   Chinese_PRC_CI_AS   NULL   ,
[录入时间]   [nvarchar]   (50)   COLLATE   Chinese_PRC_CI_AS   NULL  
)   ON   [PRIMARY]
然后再以城市名+上月的月份来命名该表

select   object_id( 'aa ')
go
declare   @mm     nvarchar(50),   @dd     nvarchar(50),   @cc   nvarchar(50),@yy   nvarchar(50)
select   @cc= 'beijing_ '
select   @yy=datename(year,getdate())
select   @mm   =datename(month,getdate())-1
select   @dd=@cc+@yy+@mm
select   @dd
exec   sp_rename   'aa ',@dd
go

小弟刚学,这样在1月的时候就不对了,望大家给指导下怎么解决这问题


------解决方案--------------------
select object_id( 'aa ')
go
declare @mm nvarchar(50), @dd nvarchar(50), @cc nvarchar(50),@yy nvarchar(50)
select @cc= 'beijing_ '
select @yy=datename(year,getdate())
select @mm =cast(month(getdate())-1 as varchar)
select @dd=@cc+@yy+@mm
select @dd
exec sp_rename 'aa ',@dd
go
------解决方案--------------------
declare @year as int
declare @month as int

set @month = month(getdate())

if @month = 1
begin
set @month = 12
set @year = year(getdate()) - 1
end
else
begin
set @month = @month - 1
set @year = year(getdate())
end