日期:2014-05-18 浏览次数:20541 次
Create proc [dbo].[prc_newtb] ( @year nvarchar(4), @moth nvarchar(2), @startdate nvarchar(10), @enddate nvarchar(10) ) AS declare @newtb nvarchar(max) declare @tablename nvarchar(50) declare @begindate1 datetime declare @enddate1 datetime declare @date datetime begin if(len(@year)<=0 or len(@moth)<=0) begin print '年份和月不能为为空!' end else begin select @tablename='tb_'+LEFT(CONVERT(varchar(100), CAST(@year+'-'+@moth+'-01' as datetime), 112),6)+'_' if(LEN(@startdate)<=0 or LEN(@enddate)<=0) begin set @tablename+='all' set @begindate1=CAST(@year+'-'+@moth+'-01' as datetime) set @enddate1=dateadd(day,-1,(DATEADD(MONTH,1,@begindate1))) end else begin set @begindate1=CAST(@year+'-'+@startdate as datetime) set @enddate1=CAST(@year+'-'+@enddate as datetime) set @tablename+='part'+(select substring(@startdate,len(@startdate)-charindex('-',reverse(@startdate))+2,8000)) set @tablename+='_'+(select substring(@enddate,len(@enddate)-charindex('-',reverse(@enddate))+2,8000)) end set @newtb='IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].['+@tablename+']'') AND type in (N''U''))' set @newtb+=' DROP TABLE [dbo].['+@tablename+']' set @newtb+=' create table '+@tablename+' ( ID int identity(1,1),RowID nvarchar(50) primary key,' set @date=@begindate1 while(@date<=@enddate1) begin set @newtb+='['+ cast(YEAR(@date) as nvarchar(4))+'-'+cast(MONTH(@date) as nvarchar(2))+'-'+CAST(DAY(@date) as nvarchar(2))+'] nvarchar(50)' if(@date<>@enddate1) begin set @newtb+=',' end set @date=DATEADD(DAY,1,@date) end set @newtb+=' )' end exec (@newtb) end