我前段时间构建了一个脚本来创建视图,而表格需要创建一个结构化视图。 SQL Server的免费版本不支持分区视图,因此我必须构建一个每晚运行的过程,创建表并根据当前数据将数据填充到每个表中,然后返回几个月的数组,6, 6-12,12-18等因为它所保存的数据太大而无法在实时系统中查询。
下面您将看到脚本中的一个关键点,它分割日期以为每个要用作视图源的分区创建表。
由于今天2月29日的6个月,这个故障实际上已经发生,这个故障今天已经发生了,这个日期在今年根本不存在!
我的问题归结为此,任何人都可以建议对下面的更正来处理不存在的日期,同时保持单独的日期范围并且不会丢失日期,以便仍然可以将任何和所有数据插入到视图中正确。这是一个艰难的。
SET @splitcount = 8
DECLARE @counter as tinyint = 1, @monthcount as tinyint,
@filter as nvarchar (200 ), @droptext as nvarchar(80)
WHILE @counter <= @splitcount
BEGIN
SET @monthcount = @counter * 6
SET @checkdate = DATEADD( month, -@monthcount , getdate ())
SET @filter = CASE WHEN @monthcount = 6 THEN 'requesteddatetime >= CAST('''+ CONVERT (varchar ( 12), @checkdate , 112) + ''' as DATETIME) AND requesteddatetime < CAST('''+ @7days+ ''' AS DATETIME)' ELSE 'requesteddatetime >= CAST(''' +CONVERT (varchar ( 12), @checkdate , 112 )+ ''' as DATETIME) AND requesteddatetime < CAST('''+ CONVERT( varchar( 12 ), DATEADD ( month , 6, @checkdate), 112 ) + ''' AS DATETIME)' END
IF @counter = @splitcount
BEGIN
SET @filter = 'requesteddatetime < CAST('''+CONVERT (varchar( 12), DATEADD(month , 6 , @checkdate ), 112 ) + ''' AS DATETIME)'
END
SET @droptext = 'DROP TABLE dbo.CustomAudit' + CAST ( @monthcount as nvarchar (50 ))+ 'Months'
IF OBJECT_ID ('dbo.CustomAudit' +CAST ( @monthcount as nvarchar( 50))+'Months' , 'U' ) IS NOT NULL
EXEC sp_executesql @droptext
SET @sql = 'CREATE Table CustomAudit'+ CAST ( @monthcount as nvarchar (50 ))+'Months (
layoutid bigint ,
displayemployeeid nvarchar (50) NULL,
forename nvarchar (50) COLLATE database_default ,
surname nvarchar (50) COLLATE database_default ,
datatablabel nvarchar (100) NOT NULL,
requesteddatetime datetime NOT NULL CHECK (' + @filter+'),
username nvarchar (50) COLLATE database_default ,
updatelevel nvarchar (50) COLLATE database_default ,
updatetype nvarchar (50) COLLATE database_default ,
field nvarchar (100) COLLATE database_default ,
CurrentValue nvarchar (800) COLLATE database_default ,
Value nvarchar (800) COLLATE database_default ,
authorised nvarchar (50) COLLATE database_default ,
authoriserdatetime datetime ,
authemployeedesc nvarchar (200),
recruitment bit,
[ID] [uniqueidentifier] NOT NULL,
CONSTRAINT PK_CustomAudit' +CAST ( @monthcount as nvarchar( 50))+'Months PRIMARY KEY CLUSTERED (surname, forename,requesteddatetime, ID)
)
CREATE NONCLUSTERED INDEX IX_' + CAST ( @monthcount as nvarchar( 50 ))+'Months_ID ON CustomAudit'+ CAST ( @monthcount as nvarchar(50 ))+'Months (displayemployeeid)
CREATE NONCLUSTERED INDEX IX_' + CAST ( @monthcount as nvarchar( 50 ))+'Months_Label ON CustomAudit'+ CAST ( @monthcount as nvarchar(50 ))+'Months (datatablabel)'
EXEC sp_executesql @sql
PRINT 'dbo.CustomAudit' +CAST ( @monthcount as nvarchar( 50))+'Months Created'
PRINT 'Filter: ' + @filter
SET @counter = @counter + 1
END