﻿/*
SystemX.DB.CPXV2Log의 배포 스크립트

이 코드는 도구를 사용하여 생성되었습니다.
파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면
변경 내용이 손실됩니다.
*/

GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;

SET NUMERIC_ROUNDABORT OFF;


GO
/*
:setvar DatabaseName "SystemX.DB.CPXV2Log"
:setvar DefaultFilePrefix "SystemX.DB.CPXV2Log"
:setvar DefaultDataPath ""
:setvar DefaultLogPath ""
*/

GO
:on error exit
GO
/*
SQLCMD 모드가 지원되지 않으면 SQLCMD 모드를 검색하고 스크립트를 실행하지 않습니다.
SQLCMD 모드를 설정한 후에 이 스크립트를 다시 사용하려면 다음을 실행합니다.
SET NOEXEC OFF; 
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
    BEGIN
        PRINT N'이 스크립트를 실행하려면 SQLCMD 모드를 사용하도록 설정해야 합니다.';
        SET NOEXEC ON;
    END


GO
USE [master];


GO

IF (DB_ID(N'$(DatabaseName)') IS NOT NULL) 
BEGIN
    ALTER DATABASE [$(DatabaseName)]
    SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    DROP DATABASE [$(DatabaseName)];
END

GO
PRINT N'$(DatabaseName) 데이터베이스를 만드는 중...'
GO
CREATE DATABASE [$(DatabaseName)] COLLATE Korean_Wansung_CI_AS
GO
USE [$(DatabaseName)];


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET ANSI_NULLS ON,
                ANSI_PADDING ON,
                ANSI_WARNINGS ON,
                ARITHABORT ON,
                CONCAT_NULL_YIELDS_NULL ON,
                NUMERIC_ROUNDABORT OFF,
                QUOTED_IDENTIFIER ON,
                ANSI_NULL_DEFAULT ON,
                CURSOR_DEFAULT LOCAL,
                RECOVERY FULL,
                CURSOR_CLOSE_ON_COMMIT OFF,
                AUTO_CREATE_STATISTICS ON,
                AUTO_SHRINK OFF,
                AUTO_UPDATE_STATISTICS ON,
                RECURSIVE_TRIGGERS OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET ALLOW_SNAPSHOT_ISOLATION OFF;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET READ_COMMITTED_SNAPSHOT OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET AUTO_UPDATE_STATISTICS_ASYNC OFF,
                PAGE_VERIFY NONE,
                DATE_CORRELATION_OPTIMIZATION OFF,
                DISABLE_BROKER,
                PARAMETERIZATION SIMPLE,
                SUPPLEMENTAL_LOGGING OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
    BEGIN
        IF EXISTS (SELECT 1
                   FROM   [master].[dbo].[sysdatabases]
                   WHERE  [name] = N'$(DatabaseName)')
            BEGIN
                EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
    SET TRUSTWORTHY OFF,
        DB_CHAINING OFF 
    WITH ROLLBACK IMMEDIATE';
            END
    END
ELSE
    BEGIN
        PRINT N'데이터베이스 설정을 수정할 수 없습니다. 이러한 설정을 적용하려면 SysAdmin이어야 합니다.';
    END


GO
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
    BEGIN
        IF EXISTS (SELECT 1
                   FROM   [master].[dbo].[sysdatabases]
                   WHERE  [name] = N'$(DatabaseName)')
            BEGIN
                EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
    SET HONOR_BROKER_PRIORITY OFF 
    WITH ROLLBACK IMMEDIATE';
            END
    END
ELSE
    BEGIN
        PRINT N'데이터베이스 설정을 수정할 수 없습니다. 이러한 설정을 적용하려면 SysAdmin이어야 합니다.';
    END


GO
ALTER DATABASE [$(DatabaseName)]
    SET TARGET_RECOVERY_TIME = 0 SECONDS 
    WITH ROLLBACK IMMEDIATE;


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF),
                CONTAINMENT = NONE 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET AUTO_CREATE_STATISTICS ON(INCREMENTAL = OFF),
                MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT = OFF,
                DELAYED_DURABILITY = DISABLED 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET QUERY_STORE (QUERY_CAPTURE_MODE = ALL, DATA_FLUSH_INTERVAL_SECONDS = 900, INTERVAL_LENGTH_MINUTES = 60, MAX_PLANS_PER_QUERY = 200, CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 367), MAX_STORAGE_SIZE_MB = 100) 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET QUERY_STORE = OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;
        ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;
        ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;
        ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;
        ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;
        ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;
        ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;
        ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET TEMPORAL_HISTORY_RETENTION ON 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF fulltextserviceproperty(N'IsFulltextInstalled') = 1
    EXECUTE sp_fulltext_database 'enable';


GO
PRINT N'테이블 [dbo].[HIST_TestResult]을(를) 만드는 중...';


GO
CREATE TABLE [dbo].[HIST_TestResult] (
    [No]      BIGINT         NOT NULL,
    [TestDT]  DATETIME2 (7)  NULL,
    [LogData] NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_HIST_TestResult] PRIMARY KEY CLUSTERED ([No] ASC) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];


GO
PRINT N'인덱스 [dbo].[HIST_TestResult].[HIST_TestResult_2]을(를) 만드는 중...';


GO
CREATE NONCLUSTERED INDEX [HIST_TestResult_2]
    ON [dbo].[HIST_TestResult]([TestDT] ASC, [No] ASC)
    ON [PRIMARY];


GO
PRINT N'인덱스 [dbo].[HIST_TestResult].[HIST_TestResult_3]을(를) 만드는 중...';


GO
CREATE NONCLUSTERED INDEX [HIST_TestResult_3]
    ON [dbo].[HIST_TestResult]([TestDT] ASC)
    ON [PRIMARY];


GO
PRINT N'테이블 [dbo].[HIST_LogSummary]을(를) 만드는 중...';


GO
CREATE TABLE [dbo].[HIST_LogSummary] (
    [No]                BIGINT         IDENTITY (0, 1) NOT NULL,
    [StationName]       NVARCHAR (128) NULL,
    [TestType]          NVARCHAR (8)   NOT NULL,
    [Version]           NVARCHAR (4)   NOT NULL,
    [ProdCode]          NVARCHAR (4)   NOT NULL,
    [TestListFileNo]    INT            NULL,
    [TestListVariantNo] INT            NULL,
    [TestListCntID]     NVARCHAR (256) NULL,
    [StepVersion]       INT            NULL,
    [HostID]            NVARCHAR (64)  NOT NULL,
    [Section]           NVARCHAR (64)  NOT NULL,
    [ProdNo_C]          NVARCHAR (32)  NOT NULL,
    [ProdNo_P]          NVARCHAR (32)  NOT NULL,
    [Testcode]          NVARCHAR (16)  NOT NULL,
    [TestListFileName]  NVARCHAR (256) NOT NULL,
    [ProductID]         NVARCHAR (64)  NOT NULL,
    [Result]            NVARCHAR (16)  NOT NULL,
    [Duration]          NVARCHAR (16)  NOT NULL,
    [TestDT]            DATETIME2 (7)  NOT NULL,
    CONSTRAINT [PK_HIST_LogSummary] PRIMARY KEY CLUSTERED ([No] ASC),
    UNIQUE NONCLUSTERED ([No] ASC) ON [PRIMARY]
) ON [PRIMARY];


GO
PRINT N'인덱스 [dbo].[HIST_LogSummary].[HIST_LogSummary_2]을(를) 만드는 중...';


GO
CREATE NONCLUSTERED INDEX [HIST_LogSummary_2]
    ON [dbo].[HIST_LogSummary]([TestDT] ASC, [No] ASC)
    ON [PRIMARY];


GO
PRINT N'인덱스 [dbo].[HIST_LogSummary].[HIST_LogSummary_3]을(를) 만드는 중...';


GO
CREATE NONCLUSTERED INDEX [HIST_LogSummary_3]
    ON [dbo].[HIST_LogSummary]([TestDT] ASC)
    ON [PRIMARY];


GO
PRINT N'DEFAULT 제약 조건 <이름 없음>을(를) 만드는 중...';


GO
ALTER TABLE [dbo].[HIST_TestResult]
    ADD DEFAULT (getdate()) FOR [TestDT];


GO
PRINT N'DEFAULT 제약 조건 <이름 없음>을(를) 만드는 중...';


GO
ALTER TABLE [dbo].[HIST_LogSummary]
    ADD DEFAULT ('-') FOR [StationName];


GO
PRINT N'DEFAULT 제약 조건 <이름 없음>을(를) 만드는 중...';


GO
ALTER TABLE [dbo].[HIST_LogSummary]
    ADD DEFAULT ((-1)) FOR [TestListFileNo];


GO
PRINT N'DEFAULT 제약 조건 <이름 없음>을(를) 만드는 중...';


GO
ALTER TABLE [dbo].[HIST_LogSummary]
    ADD DEFAULT ((-1)) FOR [TestListVariantNo];


GO
PRINT N'DEFAULT 제약 조건 <이름 없음>을(를) 만드는 중...';


GO
ALTER TABLE [dbo].[HIST_LogSummary]
    ADD DEFAULT ((-1)) FOR [StepVersion];


GO
PRINT N'DEFAULT 제약 조건 <이름 없음>을(를) 만드는 중...';


GO
ALTER TABLE [dbo].[HIST_LogSummary]
    ADD DEFAULT (getdate()) FOR [TestDT];


GO
PRINT N'프로시저 [dbo].[spCreateTableMonth]을(를) 만드는 중...';


GO
CREATE PROCEDURE [dbo].[spCreateTableMonth]
	
AS	
	--현재 월 HIST_TestResult 테이블 생성
	DECLARE @current_yymm varchar(4) = CONVERT(CHAR(4), GETDATE(), 12)

	DECLARE @current_summaryTableName varchar(40) = N'HIST_LogSummary_'+@current_yymm
	DECLARE @current_summary_query varchar(200) = N' SELECT * INTO ' + @current_summaryTableName + N' FROM HIST_LogSummary'
	IF NOT EXISTS(SELECT * FROM sys.tables WHERE NAME = @current_summaryTableName)
		BEGIN		
			EXEC(@current_summary_query)
		END

	DECLARE @current_resultTableName varchar(40) = N'HIST_TestResult_'+@current_yymm
	DECLARE @current_result_query varchar(200) = N' SELECT * INTO ' + @current_resultTableName + N' FROM HIST_TestResult'
	IF NOT EXISTS(SELECT * FROM sys.tables WHERE NAME = @current_resultTableName)
		BEGIN		
			EXEC(@current_result_query)
		END

	--다음 월 HIST_TestResult 테이블 생성
	DECLARE @next_yymm varchar(4) = CONVERT(CHAR(4), DATEADD(MONTH, 1, GETDATE()), 12)

	DECLARE @next_summaryTableName varchar(40) = N'HIST_LogSummary_'+@next_yymm
	DECLARE @next_summary_query varchar(200) = N' SELECT * INTO ' + @next_summaryTableName + N' FROM HIST_LogSummary'
	IF NOT EXISTS(SELECT * FROM sys.tables WHERE NAME = @next_summaryTableName)
		BEGIN		
			EXEC(@next_summary_query)
		END

	DECLARE @next_resultTableName varchar(40) = N'HIST_TestResult_'+@next_yymm
	DECLARE @next_result_query varchar(200) = N' SELECT * INTO ' + @next_resultTableName + N' FROM HIST_TestResult'
	IF NOT EXISTS(SELECT * FROM sys.tables WHERE NAME = @next_resultTableName)
		BEGIN		
			EXEC(@next_result_query)
		END
RETURN 0
GO
PRINT N'프로시저 [dbo].[spCreateTableByName]을(를) 만드는 중...';


GO
CREATE PROCEDURE [dbo].[spCreateTableByName]
	@logSummaryTableName nvarchar(200),
	@logResultTableName nvarchar(200)
AS	
	IF NOT EXISTS(SELECT * FROM sys.tables WHERE NAME = @logSummaryTableName)
		BEGIN		
			DECLARE @summaryQuery nvarchar(4000)= N'
			CREATE TABLE [dbo].['+@logSummaryTableName+'](
				[No] [bigint] IDENTITY(0,1) NOT NULL,
				[StationName] [nvarchar](128) NULL,
				[TestType] [nvarchar](8) NOT NULL,
				[Version] [nvarchar](4) NOT NULL,
				[ProdCode] [nvarchar](4) NOT NULL,
				[TestListFileNo] [int] NULL,
				[TestListVariantNo] [int] NULL,
				[TestListCntID] [nvarchar](256) NULL,
				[StepVersion] [int] NULL,
				[HostID] [nvarchar](64) NOT NULL,
				[Section] [nvarchar](64) NOT NULL,
				[ProdNo_C] [nvarchar](32) NOT NULL,
				[ProdNo_P] [nvarchar](32) NOT NULL,
				[Testcode] [nvarchar](16) NOT NULL,
				[TestListFileName] [nvarchar](256) NOT NULL,
				[ProductID] [nvarchar](64) NOT NULL,
				[Result] [nvarchar](16) NOT NULL,
				[Duration] [nvarchar](16) NOT NULL,
				[TestDT] [datetime2](7) NOT NULL,
				CONSTRAINT [PK_'+@logSummaryTableName+'] PRIMARY KEY CLUSTERED 
			(
				[No] ASC
			)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY],
			UNIQUE NONCLUSTERED 
			(
				[No] ASC
			)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
			) ON [PRIMARY]			

			ALTER TABLE [dbo].['+@logSummaryTableName+'] ADD  DEFAULT (''-'') FOR [StationName]
			
			ALTER TABLE [dbo].['+@logSummaryTableName+'] ADD  DEFAULT ((-1)) FOR [TestListFileNo]
			
			ALTER TABLE [dbo].['+@logSummaryTableName+'] ADD  DEFAULT ((-1)) FOR [TestListVariantNo]
			
			ALTER TABLE [dbo].['+@logSummaryTableName+'] ADD  DEFAULT ((-1)) FOR [StepVersion]
			
			ALTER TABLE [dbo].['+@logSummaryTableName+'] ADD  DEFAULT (getdate()) FOR [TestDT]					

			CREATE INDEX ['+@logSummaryTableName+'_2] ON '+@logSummaryTableName+' (TestDT, No);			

			CREATE INDEX ['+@logSummaryTableName+'_3] ON '+@logSummaryTableName+' (TestDT);			
			';

			EXEC(@summaryQuery)
		END
			
	
	IF NOT EXISTS(SELECT * FROM sys.tables WHERE NAME = @logResultTableName)
		BEGIN		
		DECLARE @resultQuery nvarchar(4000)= N'
			CREATE TABLE [dbo].['+@logResultTableName+'](
				[No] [bigint] NOT NULL,
				[TestDT] [datetime2](7) NULL,
				[LogData] [nvarchar](max) NOT NULL,
			 CONSTRAINT [PK_'+@logResultTableName+'] PRIMARY KEY CLUSTERED 
			(
				[No] ASC
			)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
			) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]		

			ALTER TABLE [dbo].['+@logResultTableName+'] ADD  DEFAULT (getdate()) FOR [TestDT]					

			CREATE INDEX ['+@logResultTableName+'_2] ON '+@logResultTableName+' (TestDT, No);			

			CREATE INDEX ['+@logResultTableName+'_3] ON '+@logResultTableName+' (TestDT);			
			';
			EXEC(@resultQuery)
		END
RETURN 0
GO
/*
배포 후 스크립트 템플릿							
--------------------------------------------------------------------------------------
 이 파일에는 빌드 스크립트에 추가될 SQL 문이 있습니다.		
 SQLCMD 구문을 사용하여 파일을 배포 후 스크립트에 포함합니다.			
 예:      :r .\myfile.sql								
 SQLCMD 구문을 사용하여 배포 후 스크립트의 변수를 참조합니다.		
 예:      :setvar TableName MyTable							
               SELECT * FROM [$(TableName)]					
--------------------------------------------------------------------------------------
*/

/*10회 루프*/
DECLARE @CNT INT = 0;
DECLARE @MAX_CNT INT = 10
DECLARE @DBNAME varchar(50) = DB_NAME();

IF (@DBNAME LIKE '%short%')
BEGIN   
    WHILE(@CNT < @MAX_CNT)
    BEGIN

        DECLARE @yyyy varchar(4) = CONVERT(CHAR(4), DATEADD(YEAR, @CNT, GETDATE()), 23)
        DECLARE @summary varchar(200) = N'HIST_LogSummary_'+@yyyy
        DECLARE @result varchar(200) = N'HIST_TestResult_'+@yyyy
        EXEC [dbo].[spCreateTableByName] @summary , @result

        SET @CNT += 1
    END
END
GO

GO
DECLARE @VarDecimalSupported AS BIT;

SELECT @VarDecimalSupported = 0;

IF ((ServerProperty(N'EngineEdition') = 3)
    AND (((@@microsoftversion / power(2, 24) = 9)
          AND (@@microsoftversion & 0xffff >= 3024))
         OR ((@@microsoftversion / power(2, 24) = 10)
             AND (@@microsoftversion & 0xffff >= 1600))))
    SELECT @VarDecimalSupported = 1;

IF (@VarDecimalSupported > 0)
    BEGIN
        EXECUTE sp_db_vardecimal_storage_format N'$(DatabaseName)', 'ON';
    END


GO
ALTER DATABASE [$(DatabaseName)]
    SET MULTI_USER 
    WITH ROLLBACK IMMEDIATE;


GO
PRINT N'업데이트가 완료되었습니다.';


GO
