问:
How to generate sql server 2012 scripts in sql server 2008 r2?
I have a script from SQL Server 2012 to create a database and I need to generate it in SQL Server 2008 R2. It create the database but no tables and views etc is created.

This is my script:

```<code>/*
Deployment script for CMS

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/
GO

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

SET NUMERIC_ROUNDABORT OFF;
GO

:setvar DatabaseName "CMS"
:setvar DefaultFilePrefix "CMS"
:setvar DefaultDataPath "C:\Program Files\Microsoft SQL
Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
:setvar DefaultLogPath "C:\Program Files\Microsoft SQL
Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
GO

:on error exit
GO

/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not
supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/

:setvar __IsSqlCmdEnabled "True"
GO

IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
    PRINT N'SQLCMD mode must be enabled to successfully execute this
script.';
    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'Creating $(DatabaseName)...'
GO
CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [$(DatabaseName)], FILENAME =
N'$(DefaultDataPath)$(DefaultFilePrefix)_Primary.mdf')
LOG ON (NAME = [$(DatabaseName)_log], FILENAME =
N'$(DefaultLogPath)$(DefaultFilePrefix)_Primary.ldf') COLLATE
SQL_Latin1_General_CP1_CI_AS
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;
    ALTER DATABASE [$(DatabaseName)]
        SET AUTO_CLOSE 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'The database settings cannot be modified. You must be a SysAdmin
to apply these settings.';
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'The database settings cannot be modified. You must be a SysAdmin
to apply these settings.';
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
USE [$(DatabaseName)];

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

GO
PRINT N'Creating [Evangelism]...';

GO
CREATE SCHEMA [Evangelism]
AUTHORIZATION [dbo];

GO
PRINT N'Creating [Evangelism].[tbl_Note]...';

GO
CREATE TABLE [Evangelism].[tbl_Note] (
[NoteId]      INT             IDENTITY (1, 1) NOT NULL,
[Description] NVARCHAR (1000) NOT NULL,
[CreatedDate] DATETIME        NOT NULL,
[UpdatedDate] DATETIME        NULL,
[ProspectId]  INT             NOT NULL,
[CreatedBy]   INT             NOT NULL,
[UpdatedBy]   INT             NULL,
CONSTRAINT [pk_Note_NoteId] PRIMARY KEY CLUSTERED ([NoteId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Address]...';

GO
CREATE TABLE [dbo].[tbl_Address] (
[AddressId]    INT            IDENTITY (1, 1) NOT NULL,
[AddressLine1] NVARCHAR (100) NOT NULL,
[AddressLine2] NVARCHAR (100) NULL,
[Postcode]     NVARCHAR (10)  NOT NULL,
[BarangayId]   INT            NULL,
[DistrictId]   INT            NULL,
[SuburbId]     INT            NULL,
[CityId]       INT            NULL,
[ProvinceId]   INT            NULL,
[StateId]      INT            NULL,
[CountryId]    INT            NULL,
CONSTRAINT [pk_Address_AddressId] PRIMARY KEY CLUSTERED ([AddressId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Barangay]...';

GO
CREATE TABLE [dbo].[tbl_Barangay] (
[BarangayId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Barangay_BarangayId] PRIMARY KEY CLUSTERED ([BarangayId]
ASC),
CONSTRAINT [uq_Barangay_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Church]...';

GO
CREATE TABLE [dbo].[tbl_Church] (
[ChurchId]      INT            IDENTITY (1, 1) NOT NULL,
[Code]          NVARCHAR (50)  NOT NULL,
[Name]          NVARCHAR (100) NOT NULL,
[ContactPerson] NVARCHAR (100) NOT NULL,
[AddressId]     INT            NOT NULL,
[ContactId]     INT            NOT NULL,
CONSTRAINT [pk_Church_ChurchId] PRIMARY KEY CLUSTERED ([ChurchId] ASC),
CONSTRAINT [uq_Church_Code] UNIQUE NONCLUSTERED ([Code] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_City]...';

GO
CREATE TABLE [dbo].[tbl_City] (
[CityId] INT            IDENTITY (1, 1) NOT NULL,
[Name]   NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_City_CityId] PRIMARY KEY CLUSTERED ([CityId] ASC),
CONSTRAINT [uq_City_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Contact]...';

GO
CREATE TABLE [dbo].[tbl_Contact] (
[ContactId]     INT            IDENTITY (1, 1) NOT NULL,
[Description]   NVARCHAR (100) NOT NULL,
[ContactTypeId] INT            NOT NULL,
CONSTRAINT [pk_Contact_ContactId] PRIMARY KEY CLUSTERED ([ContactId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_ContactType]...';

GO
CREATE TABLE [dbo].[tbl_ContactType] (
[ContactTypeId] INT            IDENTITY (1, 1) NOT NULL,
[Name]          NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_ContactType_ContactTypeId] PRIMARY KEY CLUSTERED
([ContactTypeId] ASC),
CONSTRAINT [uq_ContactType_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Country]...';

GO
CREATE TABLE [dbo].[tbl_Country] (
[CountryId] INT            IDENTITY (1, 1) NOT NULL,
[Code]      NVARCHAR (3)   NOT NULL,
[Name]      NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Country_CountryId] PRIMARY KEY CLUSTERED ([CountryId] ASC),
CONSTRAINT [uq_Country_Code] UNIQUE NONCLUSTERED ([Code] ASC),
CONSTRAINT [uq_Country_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_District]...';

GO
CREATE TABLE [dbo].[tbl_District] (
[DistrictId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_District_DistrictId] PRIMARY KEY CLUSTERED ([DistrictId]
ASC),
CONSTRAINT [uq_District_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Member]...';

GO
CREATE TABLE [dbo].[tbl_Member] (
[MemberId]    INT           IDENTITY (1, 1) NOT NULL,
[FirstName]   NVARCHAR (50) NOT NULL,
[MiddleName]  NVARCHAR (50) NULL,
[LastName]    NVARCHAR (50) NOT NULL,
[BaptismDate] DATE          NULL,
[ChurchId]    INT           NOT NULL,
[AddressId]   INT           NOT NULL,
[ContactId]   INT           NOT NULL,
CONSTRAINT [pk_Member_MemberId] PRIMARY KEY CLUSTERED ([MemberId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Prospect]...';

GO
CREATE TABLE [dbo].[tbl_Prospect] (
[ProspectId]       INT           IDENTITY (1, 1) NOT NULL,
[FirstName]        NVARCHAR (50) NOT NULL,
[MiddleName]       NVARCHAR (50) NULL,
[LastName]         NVARCHAR (50) NOT NULL,
[LastContactDate]  DATE          NOT NULL,
[ChurchId]         INT           NOT NULL,
[AssignedTo]       INT           NULL,
[AddressId]        INT           NOT NULL,
[ContactId]        INT           NOT NULL,
[ProspectStatusId] INT           NOT NULL,
CONSTRAINT [pk_Prospect_ProspectId] PRIMARY KEY CLUSTERED ([ProspectId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_ProspectStatus]...';

GO
CREATE TABLE [dbo].[tbl_ProspectStatus] (
[ProspectStatusId] INT            IDENTITY (1, 1) NOT NULL,
[Description]      NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_ProspectStatus_ProspectStatusId] PRIMARY KEY CLUSTERED
([ProspectStatusId] ASC),
CONSTRAINT [uq_ProspectStatus_Description] UNIQUE NONCLUSTERED
([Description] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Province]...';

GO
CREATE TABLE [dbo].[tbl_Province] (
[ProvinceId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Province_ProvinceId] PRIMARY KEY CLUSTERED ([ProvinceId]
ASC),
CONSTRAINT [uq_Province_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_State]...';

GO
CREATE TABLE [dbo].[tbl_State] (
[StateId] INT            IDENTITY (1, 1) NOT NULL,
[Name]    NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_State_StateId] PRIMARY KEY CLUSTERED ([StateId] ASC),
CONSTRAINT [uq_State_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Suburb]...';

GO
CREATE TABLE [dbo].[tbl_Suburb] (
[SuburbId] INT            IDENTITY (1, 1) NOT NULL,
[Name]     NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Suburb_SuburbId] PRIMARY KEY CLUSTERED ([SuburbId] ASC),
CONSTRAINT [uq_Suburb_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [Evangelism].[fk_Note_ProspectId]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_ProspectId] FOREIGN KEY ([ProspectId]) REFERENCES
[dbo].[tbl_Prospect] ([ProspectId]);

GO
PRINT N'Creating [Evangelism].[fk_Note_CreatedBy]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_CreatedBy] FOREIGN KEY ([CreatedBy]) REFERENCES
[dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [Evangelism].[fk_Note_UpdatedBy]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_UpdatedBy] FOREIGN KEY ([UpdatedBy]) REFERENCES
[dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [dbo].[fk_Address_BarangayId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_BarangayId] FOREIGN KEY ([BarangayId]) REFERENCES
[dbo].[tbl_Barangay] ([BarangayId]);

GO
PRINT N'Creating [dbo].[fk_Address_DistrictId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_DistrictId] FOREIGN KEY ([DistrictId]) REFERENCES
[dbo].[tbl_District] ([DistrictId]);

GO
PRINT N'Creating [dbo].[fk_Address_SuburbId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_SuburbId] FOREIGN KEY ([SuburbId]) REFERENCES
[dbo].[tbl_Suburb] ([SuburbId]);

GO
PRINT N'Creating [dbo].[fk_Address_CityId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_CityId] FOREIGN KEY ([CityId]) REFERENCES [dbo].
[tbl_City] ([CityId]);

GO
PRINT N'Creating [dbo].[fk_Address_ProvinceId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_ProvinceId] FOREIGN KEY ([ProvinceId]) REFERENCES
[dbo].[tbl_Province] ([ProvinceId]);

GO
PRINT N'Creating [dbo].[fk_Address_StateId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_StateId] FOREIGN KEY ([StateId]) REFERENCES
[dbo].[tbl_State] ([StateId]);

GO
PRINT N'Creating [dbo].[fk_Address_CountryId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_CountryId] FOREIGN KEY ([CountryId]) REFERENCES
[dbo].[tbl_Country] ([CountryId]);

GO
PRINT N'Creating [dbo].[fk_Church_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Church]
ADD CONSTRAINT [fk_Church_AddressId] FOREIGN KEY ([AddressId]) REFERENCES
[dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Church_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Church]
ADD CONSTRAINT [fk_Church_ContactId] FOREIGN KEY ([ContactId]) REFERENCES
[dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Contact_ContactTypeId]...';

GO
ALTER TABLE [dbo].[tbl_Contact]
ADD CONSTRAINT [fk_Contact_ContactTypeId] FOREIGN KEY ([ContactTypeId])
REFERENCES [dbo].[tbl_ContactType] ([ContactTypeId]);

GO
PRINT N'Creating [dbo].[fk_Member_ChurchId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_ChurchId] FOREIGN KEY ([ChurchId]) REFERENCES
[dbo].[tbl_Church] ([ChurchId]);

GO
PRINT N'Creating [dbo].[fk_Member_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_AddressId] FOREIGN KEY ([AddressId]) REFERENCES
[dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Member_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_ContactId] FOREIGN KEY ([ContactId]) REFERENCES
[dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ChurchId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ChurchId] FOREIGN KEY ([ChurchId]) REFERENCES
[dbo].[tbl_Church] ([ChurchId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_AssignedTo]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_AssignedTo] FOREIGN KEY ([AssignedTo])
REFERENCES [dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_AddressId] FOREIGN KEY ([AddressId]) REFERENCES
[dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ContactId] FOREIGN KEY ([ContactId]) REFERENCES
[dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ProspectStatusId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ProspectStatusId] FOREIGN KEY
([ProspectStatusId]) REFERENCES [dbo].[tbl_ProspectStatus]
([ProspectStatusId]);

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
PRINT N'Update complete.';

GO
</code>```

I got errors:

Msg 102, Level 15, State 6, Line 2

  Incorrect syntax near 'TARGET_RECOVERY_TIME'.

Msg 319, Level 15, State 1, Line 3

  Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near 'IMMEDIATE'.

An error was encountered during execution of batch. Exiting.

Hope someone could help. Thanks!

答:
Commenting out some of those statements works for me.

```<code>/*
Deployment script for CMS

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/

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

SET NUMERIC_ROUNDABORT OFF;

GO
:setvar DatabaseName "CMS"
:setvar DefaultFilePrefix "CMS"
:setvar DefaultDataPath "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
:setvar DefaultLogPath "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"

GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
    PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
    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'Creating $(DatabaseName)...'
GO
CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [$(DatabaseName)], FILENAME = N'$(DefaultDataPath)$(DefaultFilePrefix)_Primary.mdf')
LOG ON (NAME = [$(DatabaseName)_log], FILENAME = N'$(DefaultLogPath)$(DefaultFilePrefix)_Primary.ldf') COLLATE SQL_Latin1_General_CP1_CI_AS
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;
    ALTER DATABASE [$(DatabaseName)]
        SET AUTO_CLOSE 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'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
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'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
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
USE [$(DatabaseName)];

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

GO
PRINT N'Creating [Evangelism]...';

GO
CREATE SCHEMA [Evangelism]
AUTHORIZATION [dbo];

GO
PRINT N'Creating [Evangelism].[tbl_Note]...';

GO
CREATE TABLE [Evangelism].[tbl_Note] (
[NoteId]      INT             IDENTITY (1, 1) NOT NULL,
[Description] NVARCHAR (1000) NOT NULL,
[CreatedDate] DATETIME        NOT NULL,
[UpdatedDate] DATETIME        NULL,
[ProspectId]  INT             NOT NULL,
[CreatedBy]   INT             NOT NULL,
[UpdatedBy]   INT             NULL,
CONSTRAINT [pk_Note_NoteId] PRIMARY KEY CLUSTERED ([NoteId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Address]...';

GO
CREATE TABLE [dbo].[tbl_Address] (
[AddressId]    INT            IDENTITY (1, 1) NOT NULL,
[AddressLine1] NVARCHAR (100) NOT NULL,
[AddressLine2] NVARCHAR (100) NULL,
[Postcode]     NVARCHAR (10)  NOT NULL,
[BarangayId]   INT            NULL,
[DistrictId]   INT            NULL,
[SuburbId]     INT            NULL,
[CityId]       INT            NULL,
[ProvinceId]   INT            NULL,
[StateId]      INT            NULL,
[CountryId]    INT            NULL,
CONSTRAINT [pk_Address_AddressId] PRIMARY KEY CLUSTERED ([AddressId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Barangay]...';

GO
CREATE TABLE [dbo].[tbl_Barangay] (
[BarangayId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Barangay_BarangayId] PRIMARY KEY CLUSTERED ([BarangayId] ASC),
CONSTRAINT [uq_Barangay_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Church]...';

GO
CREATE TABLE [dbo].[tbl_Church] (
[ChurchId]      INT            IDENTITY (1, 1) NOT NULL,
[Code]          NVARCHAR (50)  NOT NULL,
[Name]          NVARCHAR (100) NOT NULL,
[ContactPerson] NVARCHAR (100) NOT NULL,
[AddressId]     INT            NOT NULL,
[ContactId]     INT            NOT NULL,
CONSTRAINT [pk_Church_ChurchId] PRIMARY KEY CLUSTERED ([ChurchId] ASC),
CONSTRAINT [uq_Church_Code] UNIQUE NONCLUSTERED ([Code] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_City]...';

GO
CREATE TABLE [dbo].[tbl_City] (
[CityId] INT            IDENTITY (1, 1) NOT NULL,
[Name]   NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_City_CityId] PRIMARY KEY CLUSTERED ([CityId] ASC),
CONSTRAINT [uq_City_Name] UNIQUE NONCLUSTERED ([Name] ASC)
</code>```

);

```<code>GO
PRINT N'Creating [dbo].[tbl_Contact]...';

GO
CREATE TABLE [dbo].[tbl_Contact] (
[ContactId]     INT            IDENTITY (1, 1) NOT NULL,
[Description]   NVARCHAR (100) NOT NULL,
[ContactTypeId] INT            NOT NULL,
CONSTRAINT [pk_Contact_ContactId] PRIMARY KEY CLUSTERED ([ContactId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_ContactType]...';

GO
CREATE TABLE [dbo].[tbl_ContactType] (
[ContactTypeId] INT            IDENTITY (1, 1) NOT NULL,
[Name]          NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_ContactType_ContactTypeId] PRIMARY KEY CLUSTERED ([ContactTypeId] ASC),
CONSTRAINT [uq_ContactType_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Country]...';

GO
CREATE TABLE [dbo].[tbl_Country] (
[CountryId] INT            IDENTITY (1, 1) NOT NULL,
[Code]      NVARCHAR (3)   NOT NULL,
[Name]      NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Country_CountryId] PRIMARY KEY CLUSTERED ([CountryId] ASC),
CONSTRAINT [uq_Country_Code] UNIQUE NONCLUSTERED ([Code] ASC),
CONSTRAINT [uq_Country_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_District]...';

GO
CREATE TABLE [dbo].[tbl_District] (
[DistrictId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_District_DistrictId] PRIMARY KEY CLUSTERED ([DistrictId] ASC),
CONSTRAINT [uq_District_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Member]...';

GO
CREATE TABLE [dbo].[tbl_Member] (
[MemberId]    INT           IDENTITY (1, 1) NOT NULL,
[FirstName]   NVARCHAR (50) NOT NULL,
[MiddleName]  NVARCHAR (50) NULL,
[LastName]    NVARCHAR (50) NOT NULL,
[BaptismDate] DATE          NULL,
[ChurchId]    INT           NOT NULL,
[AddressId]   INT           NOT NULL,
[ContactId]   INT           NOT NULL,
CONSTRAINT [pk_Member_MemberId] PRIMARY KEY CLUSTERED ([MemberId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Prospect]...';

GO
CREATE TABLE [dbo].[tbl_Prospect] (
[ProspectId]       INT           IDENTITY (1, 1) NOT NULL,
[FirstName]        NVARCHAR (50) NOT NULL,
[MiddleName]       NVARCHAR (50) NULL,
[LastName]         NVARCHAR (50) NOT NULL,
[LastContactDate]  DATE          NOT NULL,
[ChurchId]         INT           NOT NULL,
[AssignedTo]       INT           NULL,
[AddressId]        INT           NOT NULL,
[ContactId]        INT           NOT NULL,
[ProspectStatusId] INT           NOT NULL,
CONSTRAINT [pk_Prospect_ProspectId] PRIMARY KEY CLUSTERED ([ProspectId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_ProspectStatus]...';

GO
CREATE TABLE [dbo].[tbl_ProspectStatus] (
[ProspectStatusId] INT            IDENTITY (1, 1) NOT NULL,
[Description]      NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_ProspectStatus_ProspectStatusId] PRIMARY KEY CLUSTERED ([ProspectStatusId] ASC),
CONSTRAINT [uq_ProspectStatus_Description] UNIQUE NONCLUSTERED ([Description] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Province]...';

GO
CREATE TABLE [dbo].[tbl_Province] (
[ProvinceId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Province_ProvinceId] PRIMARY KEY CLUSTERED ([ProvinceId] ASC),
CONSTRAINT [uq_Province_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_State]...';

GO
CREATE TABLE [dbo].[tbl_State] (
[StateId] INT            IDENTITY (1, 1) NOT NULL,
[Name]    NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_State_StateId] PRIMARY KEY CLUSTERED ([StateId] ASC),
CONSTRAINT [uq_State_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Suburb]...';

GO
CREATE TABLE [dbo].[tbl_Suburb] (
[SuburbId] INT            IDENTITY (1, 1) NOT NULL,
[Name]     NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Suburb_SuburbId] PRIMARY KEY CLUSTERED ([SuburbId] ASC),
CONSTRAINT [uq_Suburb_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [Evangelism].[fk_Note_ProspectId]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_ProspectId] FOREIGN KEY ([ProspectId]) REFERENCES [dbo].[tbl_Prospect] ([ProspectId]);

GO
PRINT N'Creating [Evangelism].[fk_Note_CreatedBy]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_CreatedBy] FOREIGN KEY ([CreatedBy]) REFERENCES [dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [Evangelism].[fk_Note_UpdatedBy]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_UpdatedBy] FOREIGN KEY ([UpdatedBy]) REFERENCES [dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [dbo].[fk_Address_BarangayId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_BarangayId] FOREIGN KEY ([BarangayId]) REFERENCES [dbo].[tbl_Barangay] ([BarangayId]);

GO
PRINT N'Creating [dbo].[fk_Address_DistrictId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_DistrictId] FOREIGN KEY ([DistrictId]) REFERENCES [dbo].[tbl_District] ([DistrictId]);

GO
PRINT N'Creating [dbo].[fk_Address_SuburbId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_SuburbId] FOREIGN KEY ([SuburbId]) REFERENCES [dbo].[tbl_Suburb] ([SuburbId]);

GO
PRINT N'Creating [dbo].[fk_Address_CityId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_CityId] FOREIGN KEY ([CityId]) REFERENCES [dbo].[tbl_City] ([CityId]);

GO
PRINT N'Creating [dbo].[fk_Address_ProvinceId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_ProvinceId] FOREIGN KEY ([ProvinceId]) REFERENCES [dbo].[tbl_Province] ([ProvinceId]);

GO
PRINT N'Creating [dbo].[fk_Address_StateId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_StateId] FOREIGN KEY ([StateId]) REFERENCES [dbo].[tbl_State] ([StateId]);

GO
PRINT N'Creating [dbo].[fk_Address_CountryId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_CountryId] FOREIGN KEY ([CountryId]) REFERENCES [dbo].[tbl_Country] ([CountryId]);

GO
PRINT N'Creating [dbo].[fk_Church_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Church]
ADD CONSTRAINT [fk_Church_AddressId] FOREIGN KEY ([AddressId]) REFERENCES [dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Church_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Church]
ADD CONSTRAINT [fk_Church_ContactId] FOREIGN KEY ([ContactId]) REFERENCES [dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Contact_ContactTypeId]...';

GO
ALTER TABLE [dbo].[tbl_Contact]
ADD CONSTRAINT [fk_Contact_ContactTypeId] FOREIGN KEY ([ContactTypeId]) REFERENCES [dbo].[tbl_ContactType] ([ContactTypeId]);

GO
PRINT N'Creating [dbo].[fk_Member_ChurchId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_ChurchId] FOREIGN KEY ([ChurchId]) REFERENCES [dbo].[tbl_Church] ([ChurchId]);

GO
PRINT N'Creating [dbo].[fk_Member_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_AddressId] FOREIGN KEY ([AddressId]) REFERENCES [dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Member_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_ContactId] FOREIGN KEY ([ContactId]) REFERENCES
[dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ChurchId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ChurchId] FOREIGN KEY ([ChurchId]) REFERENCES [dbo].[tbl_Church] ([ChurchId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_AssignedTo]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_AssignedTo] FOREIGN KEY ([AssignedTo]) REFERENCES [dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_AddressId] FOREIGN KEY ([AddressId]) REFERENCES [dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ContactId] FOREIGN KEY ([ContactId]) REFERENCES [dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ProspectStatusId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ProspectStatusId] FOREIGN KEY ([ProspectStatusId]) REFERENCES [dbo].[tbl_ProspectStatus] ([ProspectStatusId]);

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
PRINT N'Update complete.';

GO
</code>```

Thanks for your help!

Body:
I have a script from SQL Server 2012 to create a database and I need to generate it in SQL Server 2008 R2. It create the database but no tables and views etc is created.

This is my script:

/*
Deployment script for CMS

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/
GO

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

SET NUMERIC_ROUNDABORT OFF;
GO

:setvar DatabaseName "CMS"
:setvar DefaultFilePrefix "CMS"
:setvar DefaultDataPath "C:\Program Files\Microsoft SQL
Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
:setvar DefaultLogPath "C:\Program Files\Microsoft SQL
Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
GO

:on error exit
GO

/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not
supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/

:setvar __IsSqlCmdEnabled "True"
GO

IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
    PRINT N'SQLCMD mode must be enabled to successfully execute this
script.';
    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'Creating $(DatabaseName)...'
GO
CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [$(DatabaseName)], FILENAME =
N'$(DefaultDataPath)$(DefaultFilePrefix)_Primary.mdf')
LOG ON (NAME = [$(DatabaseName)_log], FILENAME =
N'$(DefaultLogPath)$(DefaultFilePrefix)_Primary.ldf') COLLATE
SQL_Latin1_General_CP1_CI_AS
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;
    ALTER DATABASE [$(DatabaseName)]
        SET AUTO_CLOSE 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'The database settings cannot be modified. You must be a SysAdmin
to apply these settings.';
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'The database settings cannot be modified. You must be a SysAdmin
to apply these settings.';
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
USE [$(DatabaseName)];

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

GO
PRINT N'Creating [Evangelism]...';

GO
CREATE SCHEMA [Evangelism]
AUTHORIZATION [dbo];

GO
PRINT N'Creating [Evangelism].[tbl_Note]...';

GO
CREATE TABLE [Evangelism].[tbl_Note] (
[NoteId]      INT             IDENTITY (1, 1) NOT NULL,
[Description] NVARCHAR (1000) NOT NULL,
[CreatedDate] DATETIME        NOT NULL,
[UpdatedDate] DATETIME        NULL,
[ProspectId]  INT             NOT NULL,
[CreatedBy]   INT             NOT NULL,
[UpdatedBy]   INT             NULL,
CONSTRAINT [pk_Note_NoteId] PRIMARY KEY CLUSTERED ([NoteId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Address]...';

GO
CREATE TABLE [dbo].[tbl_Address] (
[AddressId]    INT            IDENTITY (1, 1) NOT NULL,
[AddressLine1] NVARCHAR (100) NOT NULL,
[AddressLine2] NVARCHAR (100) NULL,
[Postcode]     NVARCHAR (10)  NOT NULL,
[BarangayId]   INT            NULL,
[DistrictId]   INT            NULL,
[SuburbId]     INT            NULL,
[CityId]       INT            NULL,
[ProvinceId]   INT            NULL,
[StateId]      INT            NULL,
[CountryId]    INT            NULL,
CONSTRAINT [pk_Address_AddressId] PRIMARY KEY CLUSTERED ([AddressId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Barangay]...';

GO
CREATE TABLE [dbo].[tbl_Barangay] (
[BarangayId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Barangay_BarangayId] PRIMARY KEY CLUSTERED ([BarangayId]
ASC),
CONSTRAINT [uq_Barangay_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Church]...';

GO
CREATE TABLE [dbo].[tbl_Church] (
[ChurchId]      INT            IDENTITY (1, 1) NOT NULL,
[Code]          NVARCHAR (50)  NOT NULL,
[Name]          NVARCHAR (100) NOT NULL,
[ContactPerson] NVARCHAR (100) NOT NULL,
[AddressId]     INT            NOT NULL,
[ContactId]     INT            NOT NULL,
CONSTRAINT [pk_Church_ChurchId] PRIMARY KEY CLUSTERED ([ChurchId] ASC),
CONSTRAINT [uq_Church_Code] UNIQUE NONCLUSTERED ([Code] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_City]...';

GO
CREATE TABLE [dbo].[tbl_City] (
[CityId] INT            IDENTITY (1, 1) NOT NULL,
[Name]   NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_City_CityId] PRIMARY KEY CLUSTERED ([CityId] ASC),
CONSTRAINT [uq_City_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Contact]...';

GO
CREATE TABLE [dbo].[tbl_Contact] (
[ContactId]     INT            IDENTITY (1, 1) NOT NULL,
[Description]   NVARCHAR (100) NOT NULL,
[ContactTypeId] INT            NOT NULL,
CONSTRAINT [pk_Contact_ContactId] PRIMARY KEY CLUSTERED ([ContactId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_ContactType]...';

GO
CREATE TABLE [dbo].[tbl_ContactType] (
[ContactTypeId] INT            IDENTITY (1, 1) NOT NULL,
[Name]          NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_ContactType_ContactTypeId] PRIMARY KEY CLUSTERED
([ContactTypeId] ASC),
CONSTRAINT [uq_ContactType_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Country]...';

GO
CREATE TABLE [dbo].[tbl_Country] (
[CountryId] INT            IDENTITY (1, 1) NOT NULL,
[Code]      NVARCHAR (3)   NOT NULL,
[Name]      NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Country_CountryId] PRIMARY KEY CLUSTERED ([CountryId] ASC),
CONSTRAINT [uq_Country_Code] UNIQUE NONCLUSTERED ([Code] ASC),
CONSTRAINT [uq_Country_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_District]...';

GO
CREATE TABLE [dbo].[tbl_District] (
[DistrictId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_District_DistrictId] PRIMARY KEY CLUSTERED ([DistrictId]
ASC),
CONSTRAINT [uq_District_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Member]...';

GO
CREATE TABLE [dbo].[tbl_Member] (
[MemberId]    INT           IDENTITY (1, 1) NOT NULL,
[FirstName]   NVARCHAR (50) NOT NULL,
[MiddleName]  NVARCHAR (50) NULL,
[LastName]    NVARCHAR (50) NOT NULL,
[BaptismDate] DATE          NULL,
[ChurchId]    INT           NOT NULL,
[AddressId]   INT           NOT NULL,
[ContactId]   INT           NOT NULL,
CONSTRAINT [pk_Member_MemberId] PRIMARY KEY CLUSTERED ([MemberId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Prospect]...';

GO
CREATE TABLE [dbo].[tbl_Prospect] (
[ProspectId]       INT           IDENTITY (1, 1) NOT NULL,
[FirstName]        NVARCHAR (50) NOT NULL,
[MiddleName]       NVARCHAR (50) NULL,
[LastName]         NVARCHAR (50) NOT NULL,
[LastContactDate]  DATE          NOT NULL,
[ChurchId]         INT           NOT NULL,
[AssignedTo]       INT           NULL,
[AddressId]        INT           NOT NULL,
[ContactId]        INT           NOT NULL,
[ProspectStatusId] INT           NOT NULL,
CONSTRAINT [pk_Prospect_ProspectId] PRIMARY KEY CLUSTERED ([ProspectId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_ProspectStatus]...';

GO
CREATE TABLE [dbo].[tbl_ProspectStatus] (
[ProspectStatusId] INT            IDENTITY (1, 1) NOT NULL,
[Description]      NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_ProspectStatus_ProspectStatusId] PRIMARY KEY CLUSTERED
([ProspectStatusId] ASC),
CONSTRAINT [uq_ProspectStatus_Description] UNIQUE NONCLUSTERED
([Description] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Province]...';

GO
CREATE TABLE [dbo].[tbl_Province] (
[ProvinceId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Province_ProvinceId] PRIMARY KEY CLUSTERED ([ProvinceId]
ASC),
CONSTRAINT [uq_Province_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_State]...';

GO
CREATE TABLE [dbo].[tbl_State] (
[StateId] INT            IDENTITY (1, 1) NOT NULL,
[Name]    NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_State_StateId] PRIMARY KEY CLUSTERED ([StateId] ASC),
CONSTRAINT [uq_State_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Suburb]...';

GO
CREATE TABLE [dbo].[tbl_Suburb] (
[SuburbId] INT            IDENTITY (1, 1) NOT NULL,
[Name]     NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Suburb_SuburbId] PRIMARY KEY CLUSTERED ([SuburbId] ASC),
CONSTRAINT [uq_Suburb_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [Evangelism].[fk_Note_ProspectId]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_ProspectId] FOREIGN KEY ([ProspectId]) REFERENCES
[dbo].[tbl_Prospect] ([ProspectId]);

GO
PRINT N'Creating [Evangelism].[fk_Note_CreatedBy]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_CreatedBy] FOREIGN KEY ([CreatedBy]) REFERENCES
[dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [Evangelism].[fk_Note_UpdatedBy]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_UpdatedBy] FOREIGN KEY ([UpdatedBy]) REFERENCES
[dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [dbo].[fk_Address_BarangayId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_BarangayId] FOREIGN KEY ([BarangayId]) REFERENCES
[dbo].[tbl_Barangay] ([BarangayId]);

GO
PRINT N'Creating [dbo].[fk_Address_DistrictId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_DistrictId] FOREIGN KEY ([DistrictId]) REFERENCES
[dbo].[tbl_District] ([DistrictId]);

GO
PRINT N'Creating [dbo].[fk_Address_SuburbId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_SuburbId] FOREIGN KEY ([SuburbId]) REFERENCES
[dbo].[tbl_Suburb] ([SuburbId]);

GO
PRINT N'Creating [dbo].[fk_Address_CityId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_CityId] FOREIGN KEY ([CityId]) REFERENCES [dbo].
[tbl_City] ([CityId]);

GO
PRINT N'Creating [dbo].[fk_Address_ProvinceId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_ProvinceId] FOREIGN KEY ([ProvinceId]) REFERENCES
[dbo].[tbl_Province] ([ProvinceId]);

GO
PRINT N'Creating [dbo].[fk_Address_StateId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_StateId] FOREIGN KEY ([StateId]) REFERENCES
[dbo].[tbl_State] ([StateId]);

GO
PRINT N'Creating [dbo].[fk_Address_CountryId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_CountryId] FOREIGN KEY ([CountryId]) REFERENCES
[dbo].[tbl_Country] ([CountryId]);

GO
PRINT N'Creating [dbo].[fk_Church_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Church]
ADD CONSTRAINT [fk_Church_AddressId] FOREIGN KEY ([AddressId]) REFERENCES
[dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Church_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Church]
ADD CONSTRAINT [fk_Church_ContactId] FOREIGN KEY ([ContactId]) REFERENCES
[dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Contact_ContactTypeId]...';

GO
ALTER TABLE [dbo].[tbl_Contact]
ADD CONSTRAINT [fk_Contact_ContactTypeId] FOREIGN KEY ([ContactTypeId])
REFERENCES [dbo].[tbl_ContactType] ([ContactTypeId]);

GO
PRINT N'Creating [dbo].[fk_Member_ChurchId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_ChurchId] FOREIGN KEY ([ChurchId]) REFERENCES
[dbo].[tbl_Church] ([ChurchId]);

GO
PRINT N'Creating [dbo].[fk_Member_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_AddressId] FOREIGN KEY ([AddressId]) REFERENCES
[dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Member_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_ContactId] FOREIGN KEY ([ContactId]) REFERENCES
[dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ChurchId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ChurchId] FOREIGN KEY ([ChurchId]) REFERENCES
[dbo].[tbl_Church] ([ChurchId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_AssignedTo]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_AssignedTo] FOREIGN KEY ([AssignedTo])
REFERENCES [dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_AddressId] FOREIGN KEY ([AddressId]) REFERENCES
[dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ContactId] FOREIGN KEY ([ContactId]) REFERENCES
[dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ProspectStatusId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ProspectStatusId] FOREIGN KEY
([ProspectStatusId]) REFERENCES [dbo].[tbl_ProspectStatus]
([ProspectStatusId]);

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
PRINT N'Update complete.';

GO

I got errors:

Msg 102, Level 15, State 6, Line 2

  Incorrect syntax near 'TARGET_RECOVERY_TIME'.

Msg 319, Level 15, State 1, Line 3

  Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near 'IMMEDIATE'.

An error was encountered during execution of batch. Exiting.

Hope someone could help. Thanks!

Body:
Commenting out some of those statements works for me.

/*
Deployment script for CMS

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/

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

SET NUMERIC_ROUNDABORT OFF;

GO
:setvar DatabaseName "CMS"
:setvar DefaultFilePrefix "CMS"
:setvar DefaultDataPath "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
:setvar DefaultLogPath "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"

GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
    PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
    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'Creating $(DatabaseName)...'
GO
CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [$(DatabaseName)], FILENAME = N'$(DefaultDataPath)$(DefaultFilePrefix)_Primary.mdf')
LOG ON (NAME = [$(DatabaseName)_log], FILENAME = N'$(DefaultLogPath)$(DefaultFilePrefix)_Primary.ldf') COLLATE SQL_Latin1_General_CP1_CI_AS
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;
    ALTER DATABASE [$(DatabaseName)]
        SET AUTO_CLOSE 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'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
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'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
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
USE [$(DatabaseName)];

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

GO
PRINT N'Creating [Evangelism]...';

GO
CREATE SCHEMA [Evangelism]
AUTHORIZATION [dbo];

GO
PRINT N'Creating [Evangelism].[tbl_Note]...';

GO
CREATE TABLE [Evangelism].[tbl_Note] (
[NoteId]      INT             IDENTITY (1, 1) NOT NULL,
[Description] NVARCHAR (1000) NOT NULL,
[CreatedDate] DATETIME        NOT NULL,
[UpdatedDate] DATETIME        NULL,
[ProspectId]  INT             NOT NULL,
[CreatedBy]   INT             NOT NULL,
[UpdatedBy]   INT             NULL,
CONSTRAINT [pk_Note_NoteId] PRIMARY KEY CLUSTERED ([NoteId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Address]...';

GO
CREATE TABLE [dbo].[tbl_Address] (
[AddressId]    INT            IDENTITY (1, 1) NOT NULL,
[AddressLine1] NVARCHAR (100) NOT NULL,
[AddressLine2] NVARCHAR (100) NULL,
[Postcode]     NVARCHAR (10)  NOT NULL,
[BarangayId]   INT            NULL,
[DistrictId]   INT            NULL,
[SuburbId]     INT            NULL,
[CityId]       INT            NULL,
[ProvinceId]   INT            NULL,
[StateId]      INT            NULL,
[CountryId]    INT            NULL,
CONSTRAINT [pk_Address_AddressId] PRIMARY KEY CLUSTERED ([AddressId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Barangay]...';

GO
CREATE TABLE [dbo].[tbl_Barangay] (
[BarangayId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Barangay_BarangayId] PRIMARY KEY CLUSTERED ([BarangayId] ASC),
CONSTRAINT [uq_Barangay_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Church]...';

GO
CREATE TABLE [dbo].[tbl_Church] (
[ChurchId]      INT            IDENTITY (1, 1) NOT NULL,
[Code]          NVARCHAR (50)  NOT NULL,
[Name]          NVARCHAR (100) NOT NULL,
[ContactPerson] NVARCHAR (100) NOT NULL,
[AddressId]     INT            NOT NULL,
[ContactId]     INT            NOT NULL,
CONSTRAINT [pk_Church_ChurchId] PRIMARY KEY CLUSTERED ([ChurchId] ASC),
CONSTRAINT [uq_Church_Code] UNIQUE NONCLUSTERED ([Code] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_City]...';

GO
CREATE TABLE [dbo].[tbl_City] (
[CityId] INT            IDENTITY (1, 1) NOT NULL,
[Name]   NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_City_CityId] PRIMARY KEY CLUSTERED ([CityId] ASC),
CONSTRAINT [uq_City_Name] UNIQUE NONCLUSTERED ([Name] ASC)

);

GO
PRINT N'Creating [dbo].[tbl_Contact]...';

GO
CREATE TABLE [dbo].[tbl_Contact] (
[ContactId]     INT            IDENTITY (1, 1) NOT NULL,
[Description]   NVARCHAR (100) NOT NULL,
[ContactTypeId] INT            NOT NULL,
CONSTRAINT [pk_Contact_ContactId] PRIMARY KEY CLUSTERED ([ContactId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_ContactType]...';

GO
CREATE TABLE [dbo].[tbl_ContactType] (
[ContactTypeId] INT            IDENTITY (1, 1) NOT NULL,
[Name]          NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_ContactType_ContactTypeId] PRIMARY KEY CLUSTERED ([ContactTypeId] ASC),
CONSTRAINT [uq_ContactType_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Country]...';

GO
CREATE TABLE [dbo].[tbl_Country] (
[CountryId] INT            IDENTITY (1, 1) NOT NULL,
[Code]      NVARCHAR (3)   NOT NULL,
[Name]      NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Country_CountryId] PRIMARY KEY CLUSTERED ([CountryId] ASC),
CONSTRAINT [uq_Country_Code] UNIQUE NONCLUSTERED ([Code] ASC),
CONSTRAINT [uq_Country_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_District]...';

GO
CREATE TABLE [dbo].[tbl_District] (
[DistrictId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_District_DistrictId] PRIMARY KEY CLUSTERED ([DistrictId] ASC),
CONSTRAINT [uq_District_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Member]...';

GO
CREATE TABLE [dbo].[tbl_Member] (
[MemberId]    INT           IDENTITY (1, 1) NOT NULL,
[FirstName]   NVARCHAR (50) NOT NULL,
[MiddleName]  NVARCHAR (50) NULL,
[LastName]    NVARCHAR (50) NOT NULL,
[BaptismDate] DATE          NULL,
[ChurchId]    INT           NOT NULL,
[AddressId]   INT           NOT NULL,
[ContactId]   INT           NOT NULL,
CONSTRAINT [pk_Member_MemberId] PRIMARY KEY CLUSTERED ([MemberId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Prospect]...';

GO
CREATE TABLE [dbo].[tbl_Prospect] (
[ProspectId]       INT           IDENTITY (1, 1) NOT NULL,
[FirstName]        NVARCHAR (50) NOT NULL,
[MiddleName]       NVARCHAR (50) NULL,
[LastName]         NVARCHAR (50) NOT NULL,
[LastContactDate]  DATE          NOT NULL,
[ChurchId]         INT           NOT NULL,
[AssignedTo]       INT           NULL,
[AddressId]        INT           NOT NULL,
[ContactId]        INT           NOT NULL,
[ProspectStatusId] INT           NOT NULL,
CONSTRAINT [pk_Prospect_ProspectId] PRIMARY KEY CLUSTERED ([ProspectId] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_ProspectStatus]...';

GO
CREATE TABLE [dbo].[tbl_ProspectStatus] (
[ProspectStatusId] INT            IDENTITY (1, 1) NOT NULL,
[Description]      NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_ProspectStatus_ProspectStatusId] PRIMARY KEY CLUSTERED ([ProspectStatusId] ASC),
CONSTRAINT [uq_ProspectStatus_Description] UNIQUE NONCLUSTERED ([Description] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Province]...';

GO
CREATE TABLE [dbo].[tbl_Province] (
[ProvinceId] INT            IDENTITY (1, 1) NOT NULL,
[Name]       NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Province_ProvinceId] PRIMARY KEY CLUSTERED ([ProvinceId] ASC),
CONSTRAINT [uq_Province_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_State]...';

GO
CREATE TABLE [dbo].[tbl_State] (
[StateId] INT            IDENTITY (1, 1) NOT NULL,
[Name]    NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_State_StateId] PRIMARY KEY CLUSTERED ([StateId] ASC),
CONSTRAINT [uq_State_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [dbo].[tbl_Suburb]...';

GO
CREATE TABLE [dbo].[tbl_Suburb] (
[SuburbId] INT            IDENTITY (1, 1) NOT NULL,
[Name]     NVARCHAR (100) NOT NULL,
CONSTRAINT [pk_Suburb_SuburbId] PRIMARY KEY CLUSTERED ([SuburbId] ASC),
CONSTRAINT [uq_Suburb_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

GO
PRINT N'Creating [Evangelism].[fk_Note_ProspectId]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_ProspectId] FOREIGN KEY ([ProspectId]) REFERENCES [dbo].[tbl_Prospect] ([ProspectId]);

GO
PRINT N'Creating [Evangelism].[fk_Note_CreatedBy]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_CreatedBy] FOREIGN KEY ([CreatedBy]) REFERENCES [dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [Evangelism].[fk_Note_UpdatedBy]...';

GO
ALTER TABLE [Evangelism].[tbl_Note]
ADD CONSTRAINT [fk_Note_UpdatedBy] FOREIGN KEY ([UpdatedBy]) REFERENCES [dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [dbo].[fk_Address_BarangayId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_BarangayId] FOREIGN KEY ([BarangayId]) REFERENCES [dbo].[tbl_Barangay] ([BarangayId]);

GO
PRINT N'Creating [dbo].[fk_Address_DistrictId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_DistrictId] FOREIGN KEY ([DistrictId]) REFERENCES [dbo].[tbl_District] ([DistrictId]);

GO
PRINT N'Creating [dbo].[fk_Address_SuburbId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_SuburbId] FOREIGN KEY ([SuburbId]) REFERENCES [dbo].[tbl_Suburb] ([SuburbId]);

GO
PRINT N'Creating [dbo].[fk_Address_CityId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_CityId] FOREIGN KEY ([CityId]) REFERENCES [dbo].[tbl_City] ([CityId]);

GO
PRINT N'Creating [dbo].[fk_Address_ProvinceId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_ProvinceId] FOREIGN KEY ([ProvinceId]) REFERENCES [dbo].[tbl_Province] ([ProvinceId]);

GO
PRINT N'Creating [dbo].[fk_Address_StateId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_StateId] FOREIGN KEY ([StateId]) REFERENCES [dbo].[tbl_State] ([StateId]);

GO
PRINT N'Creating [dbo].[fk_Address_CountryId]...';

GO
ALTER TABLE [dbo].[tbl_Address]
ADD CONSTRAINT [fk_Address_CountryId] FOREIGN KEY ([CountryId]) REFERENCES [dbo].[tbl_Country] ([CountryId]);

GO
PRINT N'Creating [dbo].[fk_Church_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Church]
ADD CONSTRAINT [fk_Church_AddressId] FOREIGN KEY ([AddressId]) REFERENCES [dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Church_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Church]
ADD CONSTRAINT [fk_Church_ContactId] FOREIGN KEY ([ContactId]) REFERENCES [dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Contact_ContactTypeId]...';

GO
ALTER TABLE [dbo].[tbl_Contact]
ADD CONSTRAINT [fk_Contact_ContactTypeId] FOREIGN KEY ([ContactTypeId]) REFERENCES [dbo].[tbl_ContactType] ([ContactTypeId]);

GO
PRINT N'Creating [dbo].[fk_Member_ChurchId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_ChurchId] FOREIGN KEY ([ChurchId]) REFERENCES [dbo].[tbl_Church] ([ChurchId]);

GO
PRINT N'Creating [dbo].[fk_Member_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_AddressId] FOREIGN KEY ([AddressId]) REFERENCES [dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Member_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Member]
ADD CONSTRAINT [fk_Member_ContactId] FOREIGN KEY ([ContactId]) REFERENCES
[dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ChurchId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ChurchId] FOREIGN KEY ([ChurchId]) REFERENCES [dbo].[tbl_Church] ([ChurchId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_AssignedTo]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_AssignedTo] FOREIGN KEY ([AssignedTo]) REFERENCES [dbo].[tbl_Member] ([MemberId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_AddressId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_AddressId] FOREIGN KEY ([AddressId]) REFERENCES [dbo].[tbl_Address] ([AddressId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ContactId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ContactId] FOREIGN KEY ([ContactId]) REFERENCES [dbo].[tbl_Contact] ([ContactId]);

GO
PRINT N'Creating [dbo].[fk_Prospect_ProspectStatusId]...';

GO
ALTER TABLE [dbo].[tbl_Prospect]
ADD CONSTRAINT [fk_Prospect_ProspectStatusId] FOREIGN KEY ([ProspectStatusId]) REFERENCES [dbo].[tbl_ProspectStatus] ([ProspectStatusId]);

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
PRINT N'Update complete.';

GO

Thanks for your help!


来源: stackexchange

问:
How to convert IP address range to CIDR in Java?
I am trying to convert the IP address range into the CIDR notation in Java. Can someone provide an example of how this can be achieved?

I used the SubnetUtils for converting the CIDR to IP address range, but I can't figure out the other way round.

For example: (using http://ip2cidr.com/)

Input 1: 5.10.64.0

  Input 2: 5.10.127.255

  Result: 5.10.64.0/18

Thanks,
Dhaval

答:
```<code>public static int log2(int i) {
    int count = 0;
    i >>= 1;
    while(i > 0) {
        count++;
        i >>= 1;
    }
    return count;
}

public static List<String> range2CIDR(String startIp, String endIp) {
    List<String> res = new ArrayList<>();
    try {
        int start = ipS2I(startIp);
        int end = ipS2I(endIp);
        while(start <= end) {
            int firstNonZero = start & -start;
            int maxMask = 32 - log2(firstNonZero);
            maxMask = Math.max(maxMask, 32 - log2(end - start + 1));
            res.add(ipI2S(start) + "/" + maxMask);
            start += 1 << (32 - maxMask);
        }
    }catch(Exception e) {
        return res;
    }

    return res;
}

public static int ipS2I(String ip) throws Exception {
    String[] sa = ip.split("\\.");
    if (sa.length != 4) {
        throw new Exception("Bad ip address");
    }
    int res = 0;
    for (int i = 0; i < 4; i++) {
        int t = Integer.valueOf(sa[i]);
        if (t < 0 || t > 255) {
            throw new Exception("Bad ip address");
        }
        res += t << ((3-i) << 3);
    }
    return res;
}

public static String ipI2S(int ip) {
    StringBuilder sb = new StringBuilder();
    sb.append((ip>>24) & 0xFF).append(".").append((ip>>16)&0xFF).append(".").append((ip>>8) & 0xFF).append(".").append(ip & 0xFF);
    return sb.toString();
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
Javascript Lossy PNG image compression library
I have a (mostly) offline webapp where users can sign off with a digital signature (using this library: https://github.com/szimek/signature_pad)

The image size of a signature is about 50K, and is sent to the server as a base64 encoded json string.

Since this data is sent over satellite, I am looking to minimize the bandwidth used for each signature.

Is there any JavaScript library to do a lossy compression of the PNG to reduce the file size?

答:
I know this is a very old question, but I have something that may help.  I am assuming that the signature pad library uses the native Canvas.toDataURL function.

I looked a png saved from a canvas with the pngcheck utility and it uses RGBA - 4 bytes per pixel.  For your purposes you could use either a greyscale or palette color png that will be a much smaller size, but still lossless.

Large (2192 x 2800) greyscale PNG: 39KB

Same PNG drawn to Canvas (via DrawImage) and then saved back to an image via toDataURL: 184 KB.

Furthermore, the data inside a PNG is stored using the DEFLATE method - may libraries, like this one take a compression level as an argument, basically trading speed for size.


问:
Overwrite / update browser cookie
I have an Express 4.x app, and I pass a cookie to the browser with

```<code>res.cookie('foo','bar1', {maxAge:99999999999});
</code>```

it expires in the distant future. However, 5 minutes later, I get another request from the same user, and I want to give them a new cookie.

```<code> res.cookie('foo','bar2', {maxAge:99999999999});
</code>```

From my debugging, it looks like the new cookie doesn't overwrite the old cookie? Is that the case? How can I update/overwrite the old cookie with the new one?

答:
I am about 99% certain that using the {overwrite: true} property will do the trick - from here:

https://www.npmjs.com/package/cookies

it says:

cookies.set( name, [ value ], [ options ] ) This sets the given cookie
  in the response and returns the current context to allow chaining.

If the value is omitted, an outbound header with an expired date is
  used to delete the cookie.

If the options object is provided, it will be used to generate the
  outbound cookie header as follows:

maxAge: a number representing the milliseconds from Date.now() for
  expiry expires: a Date object indicating the cookie's expiration date
  (expires at the end of session by default). ... overwrite: a boolean
  indicating whether to overwrite previously set cookies of the same
  name (false by default). If this is true, all cookies set during the
  same request with the same name (regardless of path or domain) are
  filtered out of the Set-Cookie header when setting this cookie.

So that would be, in Node.js Express parlance:

```<code>res.cookie('cdt_app_token', encoded, {maxAge: 90000000, httpOnly: true, secure: false, overwrite: true});
</code>```

Note that if you are using a non SSL or non TLS connection, cookies may not work if secure is true.

Title: Overwrite / update browser cookie

Body:
I have an Express 4.x app, and I pass a cookie to the browser with

res.cookie('foo','bar1', {maxAge:99999999999});

it expires in the distant future. However, 5 minutes later, I get another request from the same user, and I want to give them a new cookie.

 res.cookie('foo','bar2', {maxAge:99999999999});

From my debugging, it looks like the new cookie doesn't overwrite the old cookie? Is that the case? How can I update/overwrite the old cookie with the new one?

Body:
I am about 99% certain that using the {overwrite: true} property will do the trick - from here:

https://www.npmjs.com/package/cookies

it says:

cookies.set( name, [ value ], [ options ] ) This sets the given cookie
  in the response and returns the current context to allow chaining.

If the value is omitted, an outbound header with an expired date is
  used to delete the cookie.

If the options object is provided, it will be used to generate the
  outbound cookie header as follows:

maxAge: a number representing the milliseconds from Date.now() for
  expiry expires: a Date object indicating the cookie's expiration date
  (expires at the end of session by default). ... overwrite: a boolean
  indicating whether to overwrite previously set cookies of the same
  name (false by default). If this is true, all cookies set during the
  same request with the same name (regardless of path or domain) are
  filtered out of the Set-Cookie header when setting this cookie.

So that would be, in Node.js Express parlance:

res.cookie('cdt_app_token', encoded, {maxAge: 90000000, httpOnly: true, secure: false, overwrite: true});

Note that if you are using a non SSL or non TLS connection, cookies may not work if secure is true.


问:
How do I set minimum length of my Simple_Form textarea? Ruby on Rails
I am curious about how we should change the validation setting of Simple_form so it allows me to set a minlength for my textarea. How shall we manage to do that? Thank you!</p>

答:
If you are using ruby on rails. You can easily create a form in your template view as follows

```<code>...
<%= form_tag(your_tag, method: "post") do |f| %>
<%= label_tag('your_textarea_tag', "Test:") %>
    <%= text_field_tag('your_textarea_tag', nil, required: true, minlength: 2 , maxlength: 100, size: 100) %>
<% end %>
...
</code>```

required is to make sure it is not empty.
minlength and maxlength controls the length of the content.
label_tag and label_tag is derived from actionview which is included in rails.

Body:
If you are using ruby on rails. You can easily create a form in your template view as follows

...
<%= form_tag(your_tag, method: "post") do |f| %>
<%= label_tag('your_textarea_tag', "Test:") %>
    <%= text_field_tag('your_textarea_tag', nil, required: true, minlength: 2 , maxlength: 100, size: 100) %>
<% end %>
...

required is to make sure it is not empty.
minlength and maxlength controls the length of the content.
label_tag and label_tag is derived from actionview which is included in rails.


问:
Ruby on rails updating model via rails console
I have run rails g model Task description:text. Then I have run rails console and put in a few tasks. I would now like to add more attributes to the create_tasks.rb file. Such as  .string :title.

What I tried:

opened the file(create_tasks.rb), put the new line in. Then ran rake
db:migrate then went back into the console and opened the first task
and it doesn't show the title attribute.

also tried creating a new task using the title attribute. Error:
unknown title attribute for Task.

So, how do I update the model?

答:
You need to rails db:rollback to roll the database back before the latest migration, add the new variables to the migration file, then run rails db:migrate to have the new parts of the migration file included.

If you need to roll back more revisions (if you have created more migrations since you created this model), you can either include the number of roll backs like

```<code>rails db:rollback STEP=<enter number of steps>
#e.g. rails db:rollback STEP=2
</code>```

or, you could also rails db:reset which would remove all databases, recreate them, then remigrate them.  Or you could rails db:drop to drop the database, then rails db:create and rails db:migrate to migrate the new database.

Do not edit the schema file.  The schema file is automatically updated when you run migrations etc to match the content of your migration files.

Body:
You need to rails db:rollback to roll the database back before the latest migration, add the new variables to the migration file, then run rails db:migrate to have the new parts of the migration file included.

If you need to roll back more revisions (if you have created more migrations since you created this model), you can either include the number of roll backs like

rails db:rollback STEP=<enter number of steps>
#e.g. rails db:rollback STEP=2

or, you could also rails db:reset which would remove all databases, recreate them, then remigrate them.  Or you could rails db:drop to drop the database, then rails db:create and rails db:migrate to migrate the new database.

Do not edit the schema file.  The schema file is automatically updated when you run migrations etc to match the content of your migration files.


问:
Strange Feature? of Ruby Arrays
I came around this strange feature(?) of arrays in Ruby and it would be very helpful if someone could explain to me why they work the way they do.

First lets give an example of how things usually work.

```<code>a = "Hello" #=> "Hello"
b = a #=> "Hello"
b += " Goodbye" #=> "Hello Goodbye"
b #=> "Hello Goodbye"
a #=> "Hello"
</code>```

Ok cool, when you use = it creats a copy of the object (this time a string).

But when you use arrays this happens:

```<code>a = [1,2,3] #=> [1,2,3]
b = a #=> [1,2,3]
b[1] = 5 #=> [1,5,3]
b #=> [1,5,3]
a #=> [1,5,3]
</code>```

Now thats just strange.  Its the only object I've found that doesn't get copied when using = but instead just creates a refrance to the original object.

Can someone also explain (there must be a method) for copying an array without having it point back to the original object?

答:
Actually, you should re-examine your premise.

The string assignment is really b = b + " Goodbye". The b + " Goodbye" operation returns an entirely new string, so the variable b is pointing to a new object after the assignment.

But when you assign to an individual array element, you are not creating an entirely new array, so a and b continue to point to the same object, which you just changed.

If you are looking for a rationale for the mutating vs functional behavior of arrays, it's simple. There is nothing to be gained by modifying the string. It is most likely necessary to allocate new memory anyway, so an entirely new string is created.

But an array can be arbitrarily large. Creating a new array in order to change just one element could be hugely expensive. And in any case, an array is like any other composite object.  Changing an individual attribute does not necessarily affect any other attributes.

And to answer your question, you can always do:

```<code>b = a.dup
</code>```

ContentLicense: CC BY-SA 2.5

Title: Strange Feature? of Ruby Arrays

Body:
I came around this strange feature(?) of arrays in Ruby and it would be very helpful if someone could explain to me why they work the way they do.

First lets give an example of how things usually work.

a = "Hello" #=> "Hello"
b = a #=> "Hello"
b += " Goodbye" #=> "Hello Goodbye"
b #=> "Hello Goodbye"
a #=> "Hello"

Ok cool, when you use = it creats a copy of the object (this time a string).

But when you use arrays this happens:

a = [1,2,3] #=> [1,2,3]
b = a #=> [1,2,3]
b[1] = 5 #=> [1,5,3]
b #=> [1,5,3]
a #=> [1,5,3]

Now thats just strange.  Its the only object I've found that doesn't get copied when using = but instead just creates a refrance to the original object.

Can someone also explain (there must be a method) for copying an array without having it point back to the original object?

Body:
Actually, you should re-examine your premise.

The string assignment is really b = b + " Goodbye". The b + " Goodbye" operation returns an entirely new string, so the variable b is pointing to a new object after the assignment.

But when you assign to an individual array element, you are not creating an entirely new array, so a and b continue to point to the same object, which you just changed.

If you are looking for a rationale for the mutating vs functional behavior of arrays, it's simple. There is nothing to be gained by modifying the string. It is most likely necessary to allocate new memory anyway, so an entirely new string is created.

But an array can be arbitrarily large. Creating a new array in order to change just one element could be hugely expensive. And in any case, an array is like any other composite object.  Changing an individual attribute does not necessarily affect any other attributes.

And to answer your question, you can always do:

b = a.dup


问:
Sort ObservableCollection<string> through C#
I have below ObservableCollection<string>. I need to sort this alphabetically.

```<code>private ObservableCollection<string> _animals = new ObservableCollection<string>
{
    "Cat", "Dog", "Bear", "Lion", "Mouse",
    "Horse", "Rat", "Elephant", "Kangaroo", "Lizard",
    "Snake", "Frog", "Fish", "Butterfly", "Human",
    "Cow", "Bumble Bee"
};
</code>```

I tried _animals.OrderByDescending. But I don't know how to use it correctly.

```<code>_animals.OrderByDescending(a => a.<what_is_here_?>);
</code>```

How can I do this?

答:
This is an ObservableCollection<T>, that automatically sorts itself upon a change, triggers a sort only when necessary, and only triggers a single move collection change action.

```<code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;

namespace ConsoleApp4
{
  using static Console;

  public class SortableObservableCollection<T> : ObservableCollection<T>
  {
    public Func<T, object> SortingSelector { get; set; }
    public bool Descending { get; set; }
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
      base.OnCollectionChanged(e);
      if (SortingSelector == null
          || e.Action == NotifyCollectionChangedAction.Remove
          || e.Action == NotifyCollectionChangedAction.Reset)
        return;

      var query = this
        .Select((item, index) => (Item: item, Index: index));
      query = Descending
        ? query.OrderByDescending(tuple => SortingSelector(tuple.Item))
        : query.OrderBy(tuple => SortingSelector(tuple.Item));

      var map = query.Select((tuple, index) => (OldIndex:tuple.Index, NewIndex:index))
       .Where(o => o.OldIndex != o.NewIndex);

      using (var enumerator = map.GetEnumerator())
       if (enumerator.MoveNext())
          Move(enumerator.Current.OldIndex, enumerator.Current.NewIndex);

    }
  }

  //USAGE
  class Program
  {
    static void Main(string[] args)
    {
      var xx = new SortableObservableCollection<int>() { SortingSelector = i => i };
      xx.CollectionChanged += (sender, e) =>
       WriteLine($"action: {e.Action}, oldIndex:{e.OldStartingIndex},"
         + " newIndex:{e.NewStartingIndex}, newValue: {xx[e.NewStartingIndex]}");

      xx.Add(10);
      xx.Add(8);
      xx.Add(45);
      xx.Add(0);
      xx.Add(100);
      xx.Add(-800);
      xx.Add(4857);
      xx.Add(-1);

      foreach (var item in xx)
        Write($"{item}, ");
    }
  }
}
</code>```

Output:

```<code>action: Add, oldIndex:-1, newIndex:0, newValue: 10
action: Add, oldIndex:-1, newIndex:1, newValue: 8
action: Move, oldIndex:1, newIndex:0, newValue: 8
action: Add, oldIndex:-1, newIndex:2, newValue: 45
action: Add, oldIndex:-1, newIndex:3, newValue: 0
action: Move, oldIndex:3, newIndex:0, newValue: 0
action: Add, oldIndex:-1, newIndex:4, newValue: 100
action: Add, oldIndex:-1, newIndex:5, newValue: -800
action: Move, oldIndex:5, newIndex:0, newValue: -800
action: Add, oldIndex:-1, newIndex:6, newValue: 4857
action: Add, oldIndex:-1, newIndex:7, newValue: -1
action: Move, oldIndex:7, newIndex:1, newValue: -1
-800, -1, 0, 8, 10, 45, 100, 4857,
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have below ObservableCollection<string>. I need to sort this alphabetically.

private ObservableCollection<string> _animals = new ObservableCollection<string>
{
    "Cat", "Dog", "Bear", "Lion", "Mouse",
    "Horse", "Rat", "Elephant", "Kangaroo", "Lizard",
    "Snake", "Frog", "Fish", "Butterfly", "Human",
    "Cow", "Bumble Bee"
};

I tried _animals.OrderByDescending. But I don't know how to use it correctly.

_animals.OrderByDescending(a => a.<what_is_here_?>);

How can I do this?

Body:
This is an ObservableCollection<T>, that automatically sorts itself upon a change, triggers a sort only when necessary, and only triggers a single move collection change action.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;

namespace ConsoleApp4
{
  using static Console;

  public class SortableObservableCollection<T> : ObservableCollection<T>
  {
    public Func<T, object> SortingSelector { get; set; }
    public bool Descending { get; set; }
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
      base.OnCollectionChanged(e);
      if (SortingSelector == null
          || e.Action == NotifyCollectionChangedAction.Remove
          || e.Action == NotifyCollectionChangedAction.Reset)
        return;

      var query = this
        .Select((item, index) => (Item: item, Index: index));
      query = Descending
        ? query.OrderByDescending(tuple => SortingSelector(tuple.Item))
        : query.OrderBy(tuple => SortingSelector(tuple.Item));

      var map = query.Select((tuple, index) => (OldIndex:tuple.Index, NewIndex:index))
       .Where(o => o.OldIndex != o.NewIndex);

      using (var enumerator = map.GetEnumerator())
       if (enumerator.MoveNext())
          Move(enumerator.Current.OldIndex, enumerator.Current.NewIndex);

    }
  }

  //USAGE
  class Program
  {
    static void Main(string[] args)
    {
      var xx = new SortableObservableCollection<int>() { SortingSelector = i => i };
      xx.CollectionChanged += (sender, e) =>
       WriteLine($"action: {e.Action}, oldIndex:{e.OldStartingIndex},"
         + " newIndex:{e.NewStartingIndex}, newValue: {xx[e.NewStartingIndex]}");

      xx.Add(10);
      xx.Add(8);
      xx.Add(45);
      xx.Add(0);
      xx.Add(100);
      xx.Add(-800);
      xx.Add(4857);
      xx.Add(-1);

      foreach (var item in xx)
        Write($"{item}, ");
    }
  }
}

Output:

action: Add, oldIndex:-1, newIndex:0, newValue: 10
action: Add, oldIndex:-1, newIndex:1, newValue: 8
action: Move, oldIndex:1, newIndex:0, newValue: 8
action: Add, oldIndex:-1, newIndex:2, newValue: 45
action: Add, oldIndex:-1, newIndex:3, newValue: 0
action: Move, oldIndex:3, newIndex:0, newValue: 0
action: Add, oldIndex:-1, newIndex:4, newValue: 100
action: Add, oldIndex:-1, newIndex:5, newValue: -800
action: Move, oldIndex:5, newIndex:0, newValue: -800
action: Add, oldIndex:-1, newIndex:6, newValue: 4857
action: Add, oldIndex:-1, newIndex:7, newValue: -1
action: Move, oldIndex:7, newIndex:1, newValue: -1
-800, -1, 0, 8, 10, 45, 100, 4857,


问:
Monitoring Spring boot applications : gather service/node availability data for offline reporting
I would like to gather and store data on the availability of the service or node. The day after I could summarize the figures, like { day-1: service = 98.5%; day-2 = 99%}.

I could get the data by calling a simple rest (ping) service (e.g. via Actuator or what). Then I would need to write a custom scheduled application calling the Actuator/ping services.

Is there a simple solution for collecting/storing the availability data? Via Spring Batch?

UPDATE 31-05: I read about Spring Boot Admin. Is this the right solution? See also this introduction.

The data could be extracted and formatted in a CSV, JasperReporting, etc.

答:
I hope that I can help you. I think that what you need is a way of monitoring your applications in a persistent way. You can build your own solution creating a Ping resource and scheduling a client to collect availability information from time to time. But, to no re-invent the wheel, a really suggest you use some professional tool.

I recommend that you use a Dashboard tool like Grafana to create these reports, and I suggest you try Prometheus to capture monitoring pieces of information.

I have listed some links below.

Actuator and Prometheus

monitoring-spring-boot-applications-with-prometheus

Prometheus dashboard in Grafana


问:
How to add a column with values corresponding to another column?
I will summarize how I got the dataframes I work with:

```<code>     name abundance
1    joe  1
2    tim  1
3    bob  1
4    joe  1
5    bob  1
</code>```

First I created a new dataframe by aggregating the columns and calculated what the relative freqeuency would be:

```<code>     name  abundance  relative_ab
1    joe   2          0.4
2    tim   1          0.2
3    bob   2          0.4
</code>```

But I want to add a column to the first dataframe so that there are redundant entries with the relative_ab like so (the actual data set has other information in it and I would lose the information by aggregating them).

```<code>     name abundance relative_ab
1    joe  1         0.4
2    tim  1         0.2
3    bob  1         0.4
4    joe  1         0.4
5    bob  1         0.4
</code>```

I think I could brute force this but I am relatively new to R and wondering what slick ways you guys might come up with.

Thanks!

答:
If you can use dplyr:

```<code>library(dplyr)
df %>%
  mutate(s=sum(abundance)) %>%
  group_by(name) %>%
  mutate(relative_ab=sum(abundance)/s, s=NULL)

    name abundance relative_ab
  <fctr>     <int>       <dbl>
1    joe         1         0.4
2    tim         1         0.2
3    bob         1         0.4
4    joe         1         0.4
5    bob         1         0.4
</code>```

Body:
I will summarize how I got the dataframes I work with:

     name abundance
1    joe  1
2    tim  1
3    bob  1
4    joe  1
5    bob  1

First I created a new dataframe by aggregating the columns and calculated what the relative freqeuency would be:

     name  abundance  relative_ab
1    joe   2          0.4
2    tim   1          0.2
3    bob   2          0.4

But I want to add a column to the first dataframe so that there are redundant entries with the relative_ab like so (the actual data set has other information in it and I would lose the information by aggregating them).

     name abundance relative_ab
1    joe  1         0.4
2    tim  1         0.2
3    bob  1         0.4
4    joe  1         0.4
5    bob  1         0.4

I think I could brute force this but I am relatively new to R and wondering what slick ways you guys might come up with.

Thanks!

Body:
If you can use dplyr:

library(dplyr)
df %>%
  mutate(s=sum(abundance)) %>%
  group_by(name) %>%
  mutate(relative_ab=sum(abundance)/s, s=NULL)

    name abundance relative_ab
  <fctr>     <int>       <dbl>
1    joe         1         0.4
2    tim         1         0.2
3    bob         1         0.4
4    joe         1         0.4
5    bob         1         0.4


问:
scala fastparse typechecking
I am puzzled by why the following code using scala fastparse 0.4.3 fails typechecking.

```<code>val White = WhitespaceApi.Wrapper{
  import fastparse.all._
  NoTrace(CharIn(" \t\n").rep)
}
import fastparse.noApi._
import White._

case class Term(tokens: Seq[String])
case class Terms(terms: Seq[Term])

val token = P[String] ( CharIn('a' to 'z', 'A' to 'Z', '0' to '9').rep(min=1).!)
val term: P[Term] = P("[" ~ token.!.rep(sep=" ", min=1) ~ "]").map(x => Term(x))
val terms = P("(" ~ term.!.rep(sep=" ", min=1) ~ ")").map{x => Terms(x)}
val parse = terms.parse("([ab bd ef] [xy wa dd] [jk mn op])")
</code>```

The error messages:

```<code>[error] .../MyParser.scala: type mismatch;
[error]  found   : Seq[String]
[error]  required: Seq[Term]
[error]     val terms = P("(" ~ term.!.rep(sep=" ", min=1) ~")").map{x => Terms(x)}
[error]                                                                         ^
</code>```

I would imagine that since term is of type Term and since the terms pattern uses term.!.rep(..., it should get a Seq[Term].

答:
I figured it out. My mistake was capturing (with !) redundantly in terms.  That line should instead be written:

```<code>val terms = P("(" ~ term.rep(sep=" ", min=1) ~ ")").map{x => Terms(x)}
</code>```

Notice that term.!.rep( has been rewritten to term.rep(.
Apparently capturing in any rule will return the text that the captured subrule matches overriding what the subrule actually returns.  I guess this is a feature when used correctly.  :)

Title: scala fastparse typechecking

Body:
I am puzzled by why the following code using scala fastparse 0.4.3 fails typechecking.

val White = WhitespaceApi.Wrapper{
  import fastparse.all._
  NoTrace(CharIn(" \t\n").rep)
}
import fastparse.noApi._
import White._

case class Term(tokens: Seq[String])
case class Terms(terms: Seq[Term])

val token = P[String] ( CharIn('a' to 'z', 'A' to 'Z', '0' to '9').rep(min=1).!)
val term: P[Term] = P("[" ~ token.!.rep(sep=" ", min=1) ~ "]").map(x => Term(x))
val terms = P("(" ~ term.!.rep(sep=" ", min=1) ~ ")").map{x => Terms(x)}
val parse = terms.parse("([ab bd ef] [xy wa dd] [jk mn op])")

The error messages:

[error] .../MyParser.scala: type mismatch;
[error]  found   : Seq[String]
[error]  required: Seq[Term]
[error]     val terms = P("(" ~ term.!.rep(sep=" ", min=1) ~")").map{x => Terms(x)}
[error]                                                                         ^

I would imagine that since term is of type Term and since the terms pattern uses term.!.rep(..., it should get a Seq[Term].

Body:
I figured it out. My mistake was capturing (with !) redundantly in terms.  That line should instead be written:

val terms = P("(" ~ term.rep(sep=" ", min=1) ~ ")").map{x => Terms(x)}

Notice that term.!.rep( has been rewritten to term.rep(.
Apparently capturing in any rule will return the text that the captured subrule matches overriding what the subrule actually returns.  I guess this is a feature when used correctly.  :)


问:
Wordpress - Replace main image with thumbnail when clicked
I'm trying to accomplish the following task: I have a page that has several images, 1 is large and is the main image and then several images below which are sized smaller. What I want to do is that when a user clicks one of the smaller images, that image is loaded and replaces the main product image.

An example of one of my pages is: http://footybootsdb.com/adidas-x16-1/

I would like this to occur on multiple different pages so any code that can be implemented on several pages would be appreciated.

The page is configured using the 'Page Builder' plugin for Wordpress.

答:
You can do it using js. Firstly place a big-sized image's url on the small-sized image via the data attribute like this:

```<code><div id="divContainBigSizeImage">
    <img class="small-size" src="http://main-image.jpg"
</div>
<img class="small-size" src="http://image-with-small-size.jpg" data-big-size="http://image-with-big-size.jpg">
<img class="small-size" src="http://another-image-with-small-size.jpg" data-big-size="http://another-image-with-big-size.jpg">
</code>```

Then you can bind js click event to that image to gain the big-sized image's url. If using jquery, it looks like this:

```<code>$('.small-size').on('click', function() {
    var bigSizeUrl = $(this).data('big-size'); // get the big-sized image's url
    var newImgHTML = '<img src="' + bigSizeUrl + '">'; // create an html element
    $('#divContainBigSizeImage').html(newImgHTML); // replace the current big-sized one
})
</code>```

Body:
You can do it using js. Firstly place a big-sized image's url on the small-sized image via the data attribute like this:

<div id="divContainBigSizeImage">
    <img class="small-size" src="http://main-image.jpg"
</div>
<img class="small-size" src="http://image-with-small-size.jpg" data-big-size="http://image-with-big-size.jpg">
<img class="small-size" src="http://another-image-with-small-size.jpg" data-big-size="http://another-image-with-big-size.jpg">

Then you can bind js click event to that image to gain the big-sized image's url. If using jquery, it looks like this:

$('.small-size').on('click', function() {
    var bigSizeUrl = $(this).data('big-size'); // get the big-sized image's url
    var newImgHTML = '<img src="' + bigSizeUrl + '">'; // create an html element
    $('#divContainBigSizeImage').html(newImgHTML); // replace the current big-sized one
})