View on GitHub

smallAreaHealthStatisticsUnit.github.io

Documentation for SAHSU projects, specifically the Rapid Inquiry Facility (RIF)

SQL Server data processing example log

-- ************************************************************************
--
-- Description:
--
-- Rapid Enquiry Facility (RIF) - Tile maker
--
-- Copyright:
--
-- The Rapid Inquiry Facility (RIF) is an automated tool devised by SAHSU
-- that rapidly addresses epidemiological and public health questions using
-- routinely collected health and population data and generates standardised
-- rates and relative risks for any given health outcome, for specified age
-- and year ranges, for any given geographical area.
--
-- Copyright 2014 Imperial College London, developed by the Small Area
-- Health Statistics Unit. The work of the Small Area Health Statistics Unit
-- is funded by the Public Health England as part of the MRC-PHE Centre for
-- Environment and Health. Funding for this project has also been received
-- from the Centers for Disease Control and Prevention.
--
-- This file is part of the Rapid Inquiry Facility (RIF) project.
-- RIF is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- RIF is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with RIF. If not, see <http://www.gnu.org/licenses/>; or write
-- to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301 USA
--
-- Author:
--
-- Peter Hambly, SAHSU
--
-- This script is autogenerated.
--
--
-- Create processed CSV tables created from shapefiles simplification:
--
-- a) Shapefile tables, e.g:
--    * cb_2014_us_county_500k
--    * cb_2014_us_nation_5m
--    * cb_2014_us_state_500k
-- b) Psuedo control tables copies of RIF40 control tables, e.g:
--    * geography_usa_2014
--    * geolevels_usa_2014
-- c) Processed geometry data (partitioned in PostGres), e.g:
--    * geometry_usa_2014
-- d) Hierarchy table, e.g:
--    * hierarchy_usa_2014
-- e) Lookup tables, e.g:
--    * lookup_cb_2014_us_county_500k
--    * lookup_cb_2014_us_nation_5m
--    * lookup_cb_2014_us_state_500k
-- f) Tables used to calculate tile interesections
--    * tile_blocks_usa_2014
--    * tile_intersects_usa_2014 (partitioned in PostGres)
--    * tile_limits_usa_2014
-- g) Tiles table and view
--    * t_tiles_usa_2014
--    * tiles_usa_2014
--

--
-- MS SQL Server specific parameters
--
-- Usage: sqlcmd -E -b -m-1 -e -r1 -i mssql_USA_2014.sql -v pwd="%cd%"
-- Connect flags if required: -U <username>/-E -S<myServerinstanceName>
--
-- You must set the current schema if you cannot write to the default schema!
-- You need create privilege for the various object and the bulkadmin role
--
-- USE <my database>;
--
SET QUOTED_IDENTIFIER ON;
-- SET STATISTICS TIME ON;

--
-- Set schema variable used by scripts etc to CurrentUser (defined in each relevnt GO block)
--
--

-- SQL statement 0: Start transaction >>>
BEGIN TRANSACTION;


-- SQL statement 1: NON RIF initialisation >>>
/*
 * SQL statement name: 	startup.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:			None
 *
 * Description:			Run non RIF startup script
 * Note:				% becomes % after substitution
 */

--
-- Eof;


-- SQL statement 2: Drop table cb_2014_us_county_500k >>>
IF OBJECT_ID('cb_2014_us_county_500k', 'U') IS NOT NULL DROP TABLE cb_2014_us_county_500k;


-- SQL statement 3: Create tablecb_2014_us_county_500k >>>
CREATE TABLE cb_2014_us_county_500k (
	statefp                        	NVARCHAR(1000) /* Current state Federal Information Processing Series (FIPS) code */,
	countyfp                       	NVARCHAR(1000) /* Current county Federal Information Processing Series (FIPS) code */,
	countyns                       	NVARCHAR(1000) /* Current county Geographic Names Information System (GNIS) code */,
	affgeoid                       	NVARCHAR(1000) /* American FactFinder summary level code + geovariant code + ''00US'' + GEOID */,
	geoid                          	NVARCHAR(1000) /* County identifier; a concatenation of current state Federal Information Processing Series (FIPS) code and county FIPS code */,
	name                           	NVARCHAR(1000) /* Current county name */,
	lsad                           	NVARCHAR(1000) /* Current legal/statistical area description code for county */,
	aland                          	NVARCHAR(1000) /* Current land area (square meters) */,
	awater                         	NVARCHAR(1000) /* Current water area (square meters) */,
	gid                            	integer	NOT NULL /* Unique geographic index */,
	areaid                         	varchar(100)	NOT NULL /* Area ID (COUNTYNS): Current county Geographic Names Information System (GNIS) code */,
	areaname                       	NVARCHAR(1000)	NOT NULL /* Area name (NAME): Current county name */,
	area_km2                       	numeric /* Area in square km */,
	geographic_centroid_wkt        	text /* Wellknown text for geographic centroid */,
	wkt_9                          	text /* Wellknown text for zoomlevel 9 */,
	wkt_8                          	text /* Wellknown text for zoomlevel 8 */,
	wkt_7                          	text /* Wellknown text for zoomlevel 7 */,
	wkt_6                          	text /* Wellknown text for zoomlevel 6 */);


-- SQL statement 4: Comment geospatial data table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'The County at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'The County at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k';


-- SQL statement 5: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'gid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Unique geographic index',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'gid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Unique geographic index',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'gid';


-- SQL statement 6: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'areaid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID (COUNTYNS): Current county Geographic Names Information System (GNIS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'areaid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID (COUNTYNS): Current county Geographic Names Information System (GNIS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'areaid';


-- SQL statement 7: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'areaname';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area name (NAME): Current county name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'areaname'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area name (NAME): Current county name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'areaname';


-- SQL statement 8: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'area_km2';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area in square km',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'area_km2'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area in square km',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'area_km2';


-- SQL statement 9: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'geographic_centroid_wkt';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'geographic_centroid_wkt'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'geographic_centroid_wkt';


-- SQL statement 10: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'wkt_6';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 6',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'wkt_6'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 6',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'wkt_6';


-- SQL statement 11: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'wkt_7';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 7',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'wkt_7'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 7',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'wkt_7';


-- SQL statement 12: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'wkt_8';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 8',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'wkt_8'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 8',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'wkt_8';


-- SQL statement 13: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'wkt_9';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 9',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'wkt_9'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 9',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'wkt_9';


-- SQL statement 14: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'statefp';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current state Federal Information Processing Series (FIPS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'statefp'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current state Federal Information Processing Series (FIPS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'statefp';


-- SQL statement 15: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'countyfp';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current county Federal Information Processing Series (FIPS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'countyfp'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current county Federal Information Processing Series (FIPS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'countyfp';


-- SQL statement 16: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'countyns';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current county Geographic Names Information System (GNIS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'countyns'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current county Geographic Names Information System (GNIS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'countyns';


-- SQL statement 17: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'affgeoid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'American FactFinder summary level code + geovariant code + ''00US'' + GEOID',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'affgeoid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'American FactFinder summary level code + geovariant code + ''00US'' + GEOID',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'affgeoid';


-- SQL statement 18: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'geoid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'County identifier; a concatenation of current state Federal Information Processing Series (FIPS) code and county FIPS code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'geoid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'County identifier; a concatenation of current state Federal Information Processing Series (FIPS) code and county FIPS code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'geoid';


-- SQL statement 19: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'name';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current county name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'name'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current county name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'name';


-- SQL statement 20: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'lsad';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current legal/statistical area description code for county',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'lsad'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current legal/statistical area description code for county',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'lsad';


-- SQL statement 21: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'aland';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current land area (square meters)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'aland'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current land area (square meters)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'aland';


-- SQL statement 22: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_county_500k';
SELECT @columnName  = 'awater';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current water area (square meters)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'awater'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current water area (square meters)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'awater';


-- SQL statement 23: Load table from CSV file >>>
BULK INSERT cb_2014_us_county_500k
FROM 'C:\Users\Peter\Documents\Work\usa\Tile maker USA/cb_2014_us_county_500k.csv'	-- Note use of pwd; set via -v pwd="%cd%" in the sqlcmd command line
WITH
(
	FORMATFILE = 'C:\Users\Peter\Documents\Work\usa\Tile maker USA/mssql_cb_2014_us_county_500k.fmt',		-- Use a format file
	TABLOCK					-- Table lock
);


(3233 rows affected)

-- SQL statement 24: Row check: 3233 >>>
DECLARE c1 CURSOR FOR SELECT COUNT(gid) AS total FROM cb_2014_us_county_500k;
/*
 * SQL statement name: 	csvfile_rowcheck.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: Expected number of rows; e.g. 3233
 *						3: Column to count; e.g. gid
 *
 * Description:			Check number of rows in loaded CSV file is as expected
 * Note:				%% becomes % after substitution
 */
DECLARE @c1_total AS int;
OPEN c1;
FETCH NEXT FROM c1 INTO @c1_total;
IF @c1_total = 3233
	PRINT 'Table: cb_2014_us_county_500k row check OK: ' + CAST(@c1_total AS VARCHAR);
ELSE
	RAISERROR('Table: cb_2014_us_county_500k row check FAILED: expected: 3233 got: %i', 16, 1, @c1_total);
CLOSE c1;
DEALLOCATE c1;;

Table: cb_2014_us_county_500k row check OK: 3233

-- SQL statement 25: Add primary key cb_2014_us_county_500k >>>
ALTER TABLE cb_2014_us_county_500k ADD PRIMARY KEY (gid);


-- SQL statement 26: Add unique key cb_2014_us_county_500k >>>
/*
 * SQL statement name: 	add_unique_key.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. cb_2014_us_nation_5m
 *						2: constraint name; e.g. cb_2014_us_nation_5m_uk
 *						3: fields; e.g. areaid
 *
 * Description:			Add unique key constraint
 * Note:				%% becomes % after substitution
 */
ALTER TABLE cb_2014_us_county_500k ADD CONSTRAINT cb_2014_us_county_500k_uk UNIQUE(areaid);


--
-- Add geometric  data
--

-- SQL statement 28: Add geometry column: geographic centroid >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_county_500k ADD geographic_centroid geometry
 */
ALTER TABLE cb_2014_us_county_500k ADD geographic_centroid geography;


-- SQL statement 29: Add geometry column for original SRID geometry >>>
/*
 * SQL statement name: 	add_geometry_column2.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. geometry_cb_2014_us_500k
 *						2: column name; e.g. geom
 *						3: Column SRID; e.g. 4326 [NEVER USED IN SQL SERVER, set during WKT conversion]
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON [NEVER USED IN SQL SERVER]
 *                      5: Schema (rif_data. or "")
 *
 * Description:			Add *** geometry *** column to table
 * Note:				%% becomes % after substitution
 */
ALTER TABLE cb_2014_us_county_500k ADD geom_orig geometry;


-- SQL statement 30: Add geometry column for zoomlevel: 6 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_county_500k ADD geom_6 geometry
 */
ALTER TABLE cb_2014_us_county_500k ADD geom_6 geography;


-- SQL statement 31: Add geometry column for zoomlevel: 7 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_county_500k ADD geom_7 geometry
 */
ALTER TABLE cb_2014_us_county_500k ADD geom_7 geography;


-- SQL statement 32: Add geometry column for zoomlevel: 8 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_county_500k ADD geom_8 geometry
 */
ALTER TABLE cb_2014_us_county_500k ADD geom_8 geography;


-- SQL statement 33: Add geometry column for zoomlevel: 9 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_county_500k ADD geom_9 geometry
 */
ALTER TABLE cb_2014_us_county_500k ADD geom_9 geography;


-- SQL statement 34: Update geographic centroid, geometry columns, handle polygons and mutlipolygons, convert highest zoomlevel to original SRID >>>
UPDATE cb_2014_us_county_500k
   SET geographic_centroid = geography::STGeomFromText(geographic_centroid_wkt, 4326),
       geom_6 = geography::STGeomFromText(wkt_6, 4326).MakeValid(),
       geom_7 = geography::STGeomFromText(wkt_7, 4326).MakeValid(),
       geom_8 = geography::STGeomFromText(wkt_8, 4326).MakeValid(),
       geom_9 = geography::STGeomFromText(wkt_9, 4326).MakeValid(),
       geom_orig = geometry::STGeomFromText(geometry::STGeomFromText(wkt_9, 4326).MakeValid().STAsText(), 4269);


(3233 rows affected)

--
-- Test geometry and make valid if required
--

-- SQL statement 36: Check validity of geometry columns >>>
DECLARE c1 CURSOR FOR
SELECT areaname,
       6 AS geolevel,
       geom_6.IsValidDetailed() AS reason
  FROM cb_2014_us_county_500k
 WHERE geom_6.STIsValid() = 0
UNION
SELECT areaname,
       7 AS geolevel,
       geom_7.IsValidDetailed() AS reason
  FROM cb_2014_us_county_500k
 WHERE geom_7.STIsValid() = 0
UNION
SELECT areaname,
       8 AS geolevel,
       geom_8.IsValidDetailed() AS reason
  FROM cb_2014_us_county_500k
 WHERE geom_8.STIsValid() = 0
UNION
SELECT areaname,
       9 AS geolevel,
       geom_9.IsValidDetailed() AS reason
  FROM cb_2014_us_county_500k
 WHERE geom_9.STIsValid() = 0
ORDER BY 1, 2;
DECLARE @areaname AS VARCHAR(30);
DECLARE @geolevel AS int;
DECLARE @reason AS VARCHAR(90);
DECLARE @nrows AS int;
SET @nrows=0;
OPEN c1;
FETCH NEXT FROM c1 INTO @areaname, @geolevel, @reason;
WHILE @@FETCH_STATUS = 0
BEGIN
		SET @nrows+=1;
	    PRINT 'Area: ' + @areaname + ', geolevel: ' + CAST(@geolevel AS VARCHAR) + ': ' +RTRIM(@reason);
       FETCH NEXT FROM c1 INTO @areaname, @geolevel, @reason;
END
IF @nrows = 0
	PRINT 'Table: cb_2014_us_county_500k no invalid geometry check OK';
ELSE
	RAISERROR('Table: cb_2014_us_county_500k no invalid geometry check FAILED: %i invalid', 16, 1, @nrows);
CLOSE c1;
DEALLOCATE c1;

Table: cb_2014_us_county_500k no invalid geometry check OK

--
-- Make all polygons right handed
--

-- SQL statement 38: Make all polygons right handed for zoomlevel: 6 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_6.STUnion(geom_6.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_6.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_6,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_6.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_county_500k
), b AS (
	SELECT a.gid,
	       a.geom_6,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_county_500k
   SET geom_6 = c.geom_6.ReorientObject()
  FROM cb_2014_us_county_500k c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(3012 rows affected)

-- SQL statement 39: Make all polygons right handed for zoomlevel: 7 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_7.STUnion(geom_7.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_7.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_7,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_7.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_county_500k
), b AS (
	SELECT a.gid,
	       a.geom_7,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_county_500k
   SET geom_7 = c.geom_7.ReorientObject()
  FROM cb_2014_us_county_500k c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(3016 rows affected)

-- SQL statement 40: Make all polygons right handed for zoomlevel: 8 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_8.STUnion(geom_8.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_8.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_8,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_8.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_county_500k
), b AS (
	SELECT a.gid,
	       a.geom_8,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_county_500k
   SET geom_8 = c.geom_8.ReorientObject()
  FROM cb_2014_us_county_500k c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(3016 rows affected)

-- SQL statement 41: Make all polygons right handed for zoomlevel: 9 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_9.STUnion(geom_9.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_9.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_9,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_county_500k
), b AS (
	SELECT a.gid,
	       a.geom_9,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_county_500k
   SET geom_9 = c.geom_9.ReorientObject()
  FROM cb_2014_us_county_500k c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(2993 rows affected)

--
-- Test Turf and DB areas agree to within 1%
--

--
-- Create spatial indexes
--

-- SQL statement 44: Index geometry column for zoomlevel: 6 >>>
CREATE SPATIAL INDEX cb_2014_us_county_500k_geom_6_gix ON cb_2014_us_county_500k (geom_6);


-- SQL statement 45: Index geometry column for zoomlevel: 7 >>>
CREATE SPATIAL INDEX cb_2014_us_county_500k_geom_7_gix ON cb_2014_us_county_500k (geom_7);


-- SQL statement 46: Index geometry column for zoomlevel: 8 >>>
CREATE SPATIAL INDEX cb_2014_us_county_500k_geom_8_gix ON cb_2014_us_county_500k (geom_8);


-- SQL statement 47: Index geometry column for zoomlevel: 9 >>>
CREATE SPATIAL INDEX cb_2014_us_county_500k_geom_9_gix ON cb_2014_us_county_500k (geom_9);


-- SQL statement 48: Index geometry column for original SRID geometry >>>
/*
 * SQL statement name: 	create_spatial_geometry_index.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:
 *						1: index name;e.g. geometry_cb_2014_us_500k_gix
 *						2: table name; e.g. geometry_cb_2014_us_500k
 *						3: Geometry field name; e.g. geom
 *						4: Xmin (4326); e.g. -179.13729006727
 *						5: Ymin (4326); e.g. -14.3737802873213
 *						6: Xmax (4326); e.g.  179.773803959804
 *						7: Ymax (4326); e.g. 71.352561
 *
 * Description:			Create geometry table
 * Note:				% becomes % after substitution
 */
CREATE SPATIAL INDEX cb_2014_us_county_500k_geom_orig_gix ON cb_2014_us_county_500k (geom_orig)
	WITH ( BOUNDING_BOX = (xmin=-179.148909, ymin=-14.548699000000001, xmax=179.77847, ymax=71.36516200000001));


--
-- Reports
--

-- SQL statement 50: Areas and centroids report >>>
/*
 * SQL statement name: 	area_centroid_report.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Area and centroids report
 * Note:				% becomes % after substitution
 */
WITH a AS (
	SELECT areaname, geom_9,
		   CAST(area_km2 AS NUMERIC(15,2)) AS area_km2,
		   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(15,2)) AS area_km2_calc,
		   CONCAT(
				CAST(CAST(geographic_centroid.Long AS NUMERIC(15,7)) AS VARCHAR(30)),
				',',
				CAST(CAST(geographic_centroid.Lat AS NUMERIC(15,7)) AS VARCHAR(30))
				) AS geographic_centroid,
		   CONCAT(
				CAST(CAST(geom_9.EnvelopeCenter().Long AS NUMERIC(15,7)) AS VARCHAR(30)),
				',',
				CAST(CAST(geom_9.EnvelopeCenter().Lat AS NUMERIC(15,7)) AS VARCHAR(30))
				) AS geographic_centroid_calc,
		   CAST((geom_9.EnvelopeCenter().STDistance(geographic_centroid))/1000 AS VARCHAR(30)) AS centroid_diff_km,
		   ROW_NUMBER() OVER (ORDER BY areaname) as nrow
	  FROM cb_2014_us_county_500k
)
SELECT SUBSTRING(a.areaname, 1, 30) AS areaname,
       a.area_km2,
	   a.area_km2_calc,
	   CASE WHEN area_km2 = 0 THEN NULL
			ELSE CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(15,2))
			END AS pct_km2_diff,
	   a.geographic_centroid,
       a.geographic_centroid_calc,
	   a.centroid_diff_km
  FROM a
 WHERE nrow <= 100
 ORDER BY 1 ;

areaname                       area_km2          area_km2_calc     pct_km2_diff      geographic_centroid                                           geographic_centroid_calc                                      centroid_diff_km
------------------------------ ----------------- ----------------- ----------------- ------------------------------------------------------------- ------------------------------------------------------------- ------------------------------
A+�asco                                   103.00            102.73               .26 -67.1329947,18.2847947                                        -67.1325044,18.2847397                                        0.0521983
Abbeville                                1327.00           1324.10               .22 -82.4483699,34.2237069                                        -82.4485584,34.2238219                                        0.0215487
Acadia                                   1709.00           1702.89               .36 -92.5020925,30.2284598                                        -92.5020462,30.2285459                                        0.0105366
Accomack                                 1461.00           1458.80               .15 -75.7415572,37.7658599                                        -75.7416303,37.7647998                                        0.117835
Ada                                      2748.00           2746.39               .06 -116.3414064,43.3947596                                       -116.3414340,43.3948853                                       0.0141505
Adair                                    1070.00           1067.96               .19 -85.2448719,37.2148762                                        -85.2449017,37.2149224                                        0.00575879
Adair                                    1498.00           1494.62               .23 -94.6354092,35.9174646                                        -94.6376589,35.9187746                                        0.249717
Adair                                    1476.00           1474.71               .09 -92.5540582,40.1906338                                        -92.5540548,40.1907776                                        0.0159644
Adair                                    1478.00           1477.05               .06 -94.4793820,41.3765260                                        -94.4794001,41.3766748                                        0.0165864
Adams                                    4997.00           4999.79               .06 -118.3232278,46.8748906                                       -118.3232244,46.8757480                                       0.0953205
Adams                                    1520.00           1517.62               .16 -83.4708273,38.7986072                                        -83.4691456,38.8002377                                        0.232605
Adams                                    1103.00           1102.10               .08 -94.7095814,41.0278368                                        -94.7079140,41.0299683                                        0.27514
Adams                                    1781.00           1780.61               .02 -89.8964030,43.9834049                                        -89.8962307,43.9826015                                        0.0903357
Adams                                    3547.00           3547.12               .00 -116.3207474,44.8697177                                       -116.3205724,44.8699751                                       0.0317713
Adams                                     881.00            880.42               .07 -84.9089406,40.7139760                                        -84.9148901,40.7171251                                        0.612376
Adams                                    3070.00           3065.99               .13 -104.7480496,39.8335661                                       -104.7629220,39.8410512                                       1.52029
Adams                                    1463.00           1461.18               .12 -98.4937693,40.5043052                                        -98.4936511,40.5044656                                        0.0204383
Adams                                    1267.00           1262.64               .34 -91.3981957,31.4291537                                        -91.3982394,31.4289774                                        0.0199768
Adams                                    2260.00           2257.03               .13 -91.2799451,39.9657462                                        -91.2797927,39.9659667                                        0.0277311
Adams                                    1352.00           1350.81               .09 -77.1021873,39.8976988                                        -77.1006942,39.8989300                                        0.18707
Adams                                    2560.00           2561.00               .04 -102.4693626,46.0764149                                       -102.4769747,46.0806508                                       0.753921
Addison                                  2092.00           2091.30               .03 -73.2474021,44.0346002                                        -73.2465437,44.0353366                                        0.106909
Adjuntas                                  175.00            173.78               .70 -66.7567308,18.1820164                                        -66.7566691,18.1822082                                        0.0222091
Aguada                                     81.00             80.66               .42 -67.1744735,18.3620033                                        -67.1744522,18.3617210                                        0.0313217
Aguadilla                                  95.00             95.00               .00 -67.1260072,18.4463241                                        -67.1258806,18.4464678                                        0.0207765
Aguas Buenas                               78.00             77.85               .19 -66.1315273,18.2474611                                        -66.1318908,18.2474641                                        0.0384444
Aibonito                                   82.00             81.07              1.13 -66.2550944,18.1364224                                        -66.2550942,18.1364270                                        0.000499622
Aiken                                    2806.00           2798.87               .25 -81.6527541,33.5438792                                        -81.6517808,33.5444346                                        0.109388
Aitkin                                   5166.00           5168.30               .04 -93.4591356,46.5104239                                        -93.4591257,46.5108517                                        0.0475658
Alachua                                  2518.00           2509.27               .35 -82.3110118,29.6934539                                        -82.3107893,29.6935987                                        0.0268553
Alamance                                 1128.00           1125.88               .19 -79.3433238,36.0429762                                        -79.3437866,36.0437042                                        0.0909051
Alameda                                  1953.00           1949.62               .17 -122.0271504,37.6943623                                       -122.0262002,37.6945374                                       0.0860326
Alamosa                                  1876.00           1872.77               .17 -105.6213150,37.6141980                                       -105.6214487,37.6143913                                       0.0244947
Albany                                   1382.00           1381.12               .06 -73.9152097,42.6427224                                        -73.9158903,42.6436925                                        0.121363
Albany                                  11168.00          11159.34               .08 -105.6434120,41.8968217                                       -105.6439531,41.8973914                                       0.0775917
Albemarle                                1884.00           1880.71               .17 -78.6099674,38.0189443                                        -78.6104536,38.0186137                                        0.0562968
Alcona                                   1799.00           1798.90               .01 -83.4151826,44.6896845                                        -83.4162210,44.6900574                                        0.0921638
Alcorn                                   1042.00           1039.89               .20 -88.5883902,34.8690606                                        -88.5915564,34.8649891                                        0.536495
Aleutians East                          18470.00          18513.75               .24 -161.8646726,55.0633901                                       -161.8816328,55.0790481                                       2.05238
Aleutians West                          11725.00          11746.22               .18 -163.1203838,52.8876488                                       -171.6983768,52.9782835                                       576.539
Alexander                                 656.00            654.29               .26 -89.2861988,37.1677778                                        -89.2861502,37.1678165                                        0.00609513
Alexander                                 684.00            682.84               .17 -81.2132650,35.9048252                                        -81.2127495,35.9049776                                        0.0495098
Alexandria                                 40.00             40.26               .65 -77.0897486,38.8212249                                        -77.0897596,38.8212313                                        0.00118949
Alfalfa                                  2287.00           2282.91               .18 -98.2910872,36.7485304                                        -98.2926952,36.7450536                                        0.411687
Alger                                    2427.00           2427.90               .04 -86.6694124,46.4939090                                        -86.6696400,46.4942169                                        0.0384281
Allamakee                                1707.00           1706.02               .06 -91.3007947,43.3050804                                        -91.2973176,43.3006606                                        0.56631
Allegan                                  2184.00           2182.24               .08 -85.9838968,42.6054525                                        -85.9820538,42.6045543                                        0.181191
Allegany                                 2680.00           2678.84               .04 -78.0523961,42.2850097                                        -78.0525736,42.2876490                                        0.293529
Allegany                                 1115.00           1113.31               .15 -78.6507138,39.5873252                                        -78.6491418,39.5872161                                        0.135589
Alleghany                                1165.00           1162.66               .20 -80.0135796,37.7752220                                        -80.0130991,37.7757193                                        0.0695651
Alleghany                                 614.00            612.81               .19 -81.1691020,36.4617981                                        -81.1702246,36.4613710                                        0.111234
Allegheny                                1930.00           1928.12               .10 -79.9145901,40.4591042                                        -79.9145256,40.4592694                                        0.0191408
Allen                                    1711.00           1709.53               .09 -85.0688313,41.1036465                                        -85.0727680,41.1014468                                        0.411141
Allen                                    1311.00           1308.72               .17 -95.3228227,37.8727931                                        -95.3204597,37.8753425                                        0.351137
Allen                                    1055.00           1053.69               .12 -84.1308842,40.7963831                                        -84.1309026,40.7965299                                        0.0163763
Allen                                     914.00            911.90               .23 -86.1720311,36.8197629                                        -86.1720599,36.8198344                                        0.00834114
Allen                                    1991.00           1984.74               .31 -92.7147705,30.5998019                                        -92.7147495,30.5999032                                        0.0114082
Allendale                                1072.00           1068.61               .32 -81.4095984,32.9610623                                        -81.4096167,32.9611381                                        0.00857498
Alpena                                   1550.00           1550.22               .01 -83.3848734,45.0386846                                        -83.3844861,45.0392376                                        0.0686131
Alpine                                   1927.00           1924.14               .15 -119.7196689,38.5990838                                       -119.7194543,38.5991965                                       0.0224931
Amador                                   1572.00           1569.81               .14 -120.5714313,38.4765541                                       -120.5716694,38.4768913                                       0.0428119
Amelia                                    930.00            928.97               .11 -77.8946962,37.3579765                                        -77.8945415,37.3581087                                        0.0200751
Amherst                                  1242.00           1240.28               .14 -79.1476102,37.6131428                                        -79.1475422,37.6132472                                        0.013051
Amite                                    1901.00           1894.63               .34 -90.9189620,31.2349871                                        -90.9199831,31.2366039                                        0.203953
Anchorage                                4471.00           4487.66               .37 -149.6095495,61.1353294                                       -149.6088626,61.1358987                                       0.0734407
Anderson                                  895.00            893.00               .22 -84.1844937,36.1310079                                        -84.1842111,36.1313227                                        0.0432127
Anderson                                 1966.00           1961.76               .22 -82.5749099,34.5759782                                        -82.5750844,34.5761367                                        0.023784
Anderson                                 2800.00           2791.89               .29 -95.6383847,31.7958845                                        -95.6383297,31.7961713                                        0.0322193
Anderson                                  530.00            529.21               .15 -85.0100877,37.9870321                                        -85.0101366,37.9870850                                        0.00726859
Anderson                                 1514.00           1512.06               .13 -95.3190191,38.2336821                                        -95.3190391,38.2338204                                        0.0154554
Andrew                                   1132.00           1130.36               .14 -94.9604314,40.0028543                                        -94.9603557,40.0029186                                        0.0096379
Andrews                                  3899.00           3888.16               .28 -102.6321596,32.3234219                                       -102.6322617,32.3238800                                       0.0517011
Androscoggin                             1288.00           1287.61               .03 -70.1857595,44.1219602                                        -70.1857558,44.1220811                                        0.0134369
Angelina                                 2246.00           2239.66               .28 -94.6294988,31.2728291                                        -94.6295237,31.2732321                                        0.0447448
Anne Arundel                             1166.00           1164.06               .17 -76.5992537,38.9754998                                        -76.5996931,38.9764674                                        0.113973
Anoka                                    1155.00           1155.30               .03 -93.2702379,45.1930631                                        -93.2712826,45.1935578                                        0.0988042
Anson                                    1394.00           1390.93               .22 -80.0852336,35.1134175                                        -80.0888394,35.1139737                                        0.334451
Antelope                                 2225.00           2223.54               .07 -98.0726111,42.1476394                                        -98.0726155,42.1478068                                        0.0185938
Antrim                                   1360.00           1360.42               .03 -85.3078535,45.0016980                                        -85.3071041,45.0012259                                        0.079019
Apache                                  29122.00          29057.98               .22 -109.5479814,34.3181105                                       -109.5531389,34.2971350                                       2.37471
Appanoose                                1338.00           1336.90               .08 -92.8445085,40.7178591                                        -92.8444727,40.7179967                                        0.0155775
Appling                                  1330.00           1326.42               .27 -82.2735127,31.7919500                                        -82.2735341,31.7920218                                        0.00821402
Appomattox                                868.00            866.23               .20 -78.7932450,37.3693304                                        -78.7931901,37.3694045                                        0.0095547
Aransas                                   758.00            755.21               .37 -97.0070509,28.0885995                                        -97.0068823,28.0884778                                        0.0213678
Arapahoe                                 2089.00           2085.89               .15 -104.8085219,39.6633871                                       -104.8222628,39.6602379                                       1.22991
Archer                                   2403.00           2396.86               .26 -98.6033509,33.6476709                                        -98.6049576,33.6442682                                        0.405774
Archuleta                                3515.00           3509.05               .17 -107.0220661,37.1521723                                       -107.0296557,37.1619826                                       1.28059
Arecibo                                   331.00            329.24               .53 -66.6714573,18.3949278                                        -66.6708670,18.3939088                                        0.128889
Arenac                                    963.00            962.85               .02 -83.7479829,44.0239295                                        -83.7480225,44.0240604                                        0.0148812
Arkansas                                 2684.00           2677.43               .24 -91.2712196,34.2148235                                        -91.2712316,34.2149545                                        0.0145785
Arlington                                  67.00             67.31               .46 -77.0916376,38.8721719                                        -77.0916298,38.8721755                                        0.000782702
Armstrong                                2372.00           2366.94               .21 -101.3911343,34.9517569                                       -101.3911668,34.9519752                                       0.024394
Armstrong                                1721.00           1719.23               .10 -79.5052822,40.8833088                                        -79.5053319,40.8833917                                        0.010114
Aroostook                               17676.00          17681.34               .03 -68.4708284,46.9148238                                        -68.4686555,46.9172695                                        0.318305
Arroyo                                     39.00             39.04               .10 -66.0577185,17.9938805                                        -66.0577530,17.9949967                                        0.123597
Arthur                                   1862.00           1860.12               .10 -101.5804802,41.5939187                                       -101.5803929,41.5941061                                       0.0220469
Ascension                                 787.00            784.06               .37 -90.8415767,30.2516738                                        -90.8415768,30.2517327                                        0.00652508
Ashe                                     1114.00           1111.94               .18 -81.4677509,36.4019679                                        -81.4666564,36.4012441                                        0.126848
Ashland                                  2735.00           2736.02               .04 -90.6546769,46.8236372                                        -90.6540367,46.8243990                                        0.0977693
Ashland                                  1107.00           1105.52               .13 -82.2976924,40.8081443                                        -82.2965228,40.8061121                                        0.246312

(100 rows affected)

-- SQL statement 51: Drop table cb_2014_us_nation_5m >>>
IF OBJECT_ID('cb_2014_us_nation_5m', 'U') IS NOT NULL DROP TABLE cb_2014_us_nation_5m;


-- SQL statement 52: Create tablecb_2014_us_nation_5m >>>
CREATE TABLE cb_2014_us_nation_5m (
	affgeoid                       	NVARCHAR(1000) /* American FactFinder summary level code + geovariant code + ''00US'' */,
	geoid                          	NVARCHAR(1000) /* Nation identifier */,
	name                           	NVARCHAR(1000) /* Nation name */,
	gid                            	integer	NOT NULL /* Unique geographic index */,
	areaid                         	varchar(100)	NOT NULL /* Area ID (GEOID): Nation identifier */,
	areaname                       	NVARCHAR(1000)	NOT NULL /* Area name (NAME): Nation name */,
	area_km2                       	numeric /* Area in square km */,
	geographic_centroid_wkt        	text /* Wellknown text for geographic centroid */,
	wkt_9                          	text /* Wellknown text for zoomlevel 9 */,
	wkt_8                          	text /* Wellknown text for zoomlevel 8 */,
	wkt_7                          	text /* Wellknown text for zoomlevel 7 */,
	wkt_6                          	text /* Wellknown text for zoomlevel 6 */);


-- SQL statement 53: Comment geospatial data table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'The nation at a scale of 1:5,000,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'The nation at a scale of 1:5,000,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m';


-- SQL statement 54: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'gid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Unique geographic index',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'gid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Unique geographic index',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'gid';


-- SQL statement 55: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'areaid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID (GEOID): Nation identifier',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'areaid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID (GEOID): Nation identifier',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'areaid';


-- SQL statement 56: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'areaname';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area name (NAME): Nation name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'areaname'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area name (NAME): Nation name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'areaname';


-- SQL statement 57: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'area_km2';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area in square km',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'area_km2'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area in square km',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'area_km2';


-- SQL statement 58: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'geographic_centroid_wkt';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'geographic_centroid_wkt'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'geographic_centroid_wkt';


-- SQL statement 59: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'wkt_6';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 6',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'wkt_6'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 6',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'wkt_6';


-- SQL statement 60: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'wkt_7';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 7',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'wkt_7'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 7',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'wkt_7';


-- SQL statement 61: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'wkt_8';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 8',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'wkt_8'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 8',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'wkt_8';


-- SQL statement 62: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'wkt_9';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 9',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'wkt_9'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 9',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'wkt_9';


-- SQL statement 63: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'affgeoid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'American FactFinder summary level code + geovariant code + ''00US''',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'affgeoid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'American FactFinder summary level code + geovariant code + ''00US''',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'affgeoid';


-- SQL statement 64: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'geoid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Nation identifier',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'geoid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Nation identifier',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'geoid';


-- SQL statement 65: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_nation_5m';
SELECT @columnName  = 'name';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Nation name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'name'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Nation name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'name';


-- SQL statement 66: Load table from CSV file >>>
BULK INSERT cb_2014_us_nation_5m
FROM 'C:\Users\Peter\Documents\Work\usa\Tile maker USA/cb_2014_us_nation_5m.csv'	-- Note use of pwd; set via -v pwd="%cd%" in the sqlcmd command line
WITH
(
	FORMATFILE = 'C:\Users\Peter\Documents\Work\usa\Tile maker USA/mssql_cb_2014_us_nation_5m.fmt',		-- Use a format file
	TABLOCK					-- Table lock
);


(1 rows affected)

-- SQL statement 67: Row check: 1 >>>
DECLARE c1 CURSOR FOR SELECT COUNT(gid) AS total FROM cb_2014_us_nation_5m;
/*
 * SQL statement name: 	csvfile_rowcheck.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: Expected number of rows; e.g. 3233
 *						3: Column to count; e.g. gid
 *
 * Description:			Check number of rows in loaded CSV file is as expected
 * Note:				%% becomes % after substitution
 */
DECLARE @c1_total AS int;
OPEN c1;
FETCH NEXT FROM c1 INTO @c1_total;
IF @c1_total = 1
	PRINT 'Table: cb_2014_us_nation_5m row check OK: ' + CAST(@c1_total AS VARCHAR);
ELSE
	RAISERROR('Table: cb_2014_us_nation_5m row check FAILED: expected: 1 got: %i', 16, 1, @c1_total);
CLOSE c1;
DEALLOCATE c1;;

Table: cb_2014_us_nation_5m row check OK: 1

-- SQL statement 68: Add primary key cb_2014_us_nation_5m >>>
ALTER TABLE cb_2014_us_nation_5m ADD PRIMARY KEY (gid);


-- SQL statement 69: Add unique key cb_2014_us_nation_5m >>>
/*
 * SQL statement name: 	add_unique_key.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. cb_2014_us_nation_5m
 *						2: constraint name; e.g. cb_2014_us_nation_5m_uk
 *						3: fields; e.g. areaid
 *
 * Description:			Add unique key constraint
 * Note:				%% becomes % after substitution
 */
ALTER TABLE cb_2014_us_nation_5m ADD CONSTRAINT cb_2014_us_nation_5m_uk UNIQUE(areaid);


--
-- Add geometric  data
--

-- SQL statement 71: Add geometry column: geographic centroid >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_nation_5m ADD geographic_centroid geometry
 */
ALTER TABLE cb_2014_us_nation_5m ADD geographic_centroid geography;


-- SQL statement 72: Add geometry column for original SRID geometry >>>
/*
 * SQL statement name: 	add_geometry_column2.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. geometry_cb_2014_us_500k
 *						2: column name; e.g. geom
 *						3: Column SRID; e.g. 4326 [NEVER USED IN SQL SERVER, set during WKT conversion]
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON [NEVER USED IN SQL SERVER]
 *                      5: Schema (rif_data. or "")
 *
 * Description:			Add *** geometry *** column to table
 * Note:				%% becomes % after substitution
 */
ALTER TABLE cb_2014_us_nation_5m ADD geom_orig geometry;


-- SQL statement 73: Add geometry column for zoomlevel: 6 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_nation_5m ADD geom_6 geometry
 */
ALTER TABLE cb_2014_us_nation_5m ADD geom_6 geography;


-- SQL statement 74: Add geometry column for zoomlevel: 7 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_nation_5m ADD geom_7 geometry
 */
ALTER TABLE cb_2014_us_nation_5m ADD geom_7 geography;


-- SQL statement 75: Add geometry column for zoomlevel: 8 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_nation_5m ADD geom_8 geometry
 */
ALTER TABLE cb_2014_us_nation_5m ADD geom_8 geography;


-- SQL statement 76: Add geometry column for zoomlevel: 9 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_nation_5m ADD geom_9 geometry
 */
ALTER TABLE cb_2014_us_nation_5m ADD geom_9 geography;


-- SQL statement 77: Update geographic centroid, geometry columns, handle polygons and mutlipolygons, convert highest zoomlevel to original SRID >>>
UPDATE cb_2014_us_nation_5m
   SET geographic_centroid = geography::STGeomFromText(geographic_centroid_wkt, 4326),
       geom_6 = geography::STGeomFromText(wkt_6, 4326).MakeValid(),
       geom_7 = geography::STGeomFromText(wkt_7, 4326).MakeValid(),
       geom_8 = geography::STGeomFromText(wkt_8, 4326).MakeValid(),
       geom_9 = geography::STGeomFromText(wkt_9, 4326).MakeValid(),
       geom_orig = geometry::STGeomFromText(geometry::STGeomFromText(wkt_9, 4326).MakeValid().STAsText(), 4269);


(1 rows affected)

--
-- Test geometry and make valid if required
--

-- SQL statement 79: Check validity of geometry columns >>>
DECLARE c1 CURSOR FOR
SELECT areaname,
       6 AS geolevel,
       geom_6.IsValidDetailed() AS reason
  FROM cb_2014_us_nation_5m
 WHERE geom_6.STIsValid() = 0
UNION
SELECT areaname,
       7 AS geolevel,
       geom_7.IsValidDetailed() AS reason
  FROM cb_2014_us_nation_5m
 WHERE geom_7.STIsValid() = 0
UNION
SELECT areaname,
       8 AS geolevel,
       geom_8.IsValidDetailed() AS reason
  FROM cb_2014_us_nation_5m
 WHERE geom_8.STIsValid() = 0
UNION
SELECT areaname,
       9 AS geolevel,
       geom_9.IsValidDetailed() AS reason
  FROM cb_2014_us_nation_5m
 WHERE geom_9.STIsValid() = 0
ORDER BY 1, 2;
DECLARE @areaname AS VARCHAR(30);
DECLARE @geolevel AS int;
DECLARE @reason AS VARCHAR(90);
DECLARE @nrows AS int;
SET @nrows=0;
OPEN c1;
FETCH NEXT FROM c1 INTO @areaname, @geolevel, @reason;
WHILE @@FETCH_STATUS = 0
BEGIN
		SET @nrows+=1;
	    PRINT 'Area: ' + @areaname + ', geolevel: ' + CAST(@geolevel AS VARCHAR) + ': ' +RTRIM(@reason);
       FETCH NEXT FROM c1 INTO @areaname, @geolevel, @reason;
END
IF @nrows = 0
	PRINT 'Table: cb_2014_us_nation_5m no invalid geometry check OK';
ELSE
	RAISERROR('Table: cb_2014_us_nation_5m no invalid geometry check FAILED: %i invalid', 16, 1, @nrows);
CLOSE c1;
DEALLOCATE c1;

Table: cb_2014_us_nation_5m no invalid geometry check OK

--
-- Make all polygons right handed
--

-- SQL statement 81: Make all polygons right handed for zoomlevel: 6 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_6.STUnion(geom_6.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_6.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_6,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_6.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_nation_5m
), b AS (
	SELECT a.gid,
	       a.geom_6,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_nation_5m
   SET geom_6 = c.geom_6.ReorientObject()
  FROM cb_2014_us_nation_5m c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(0 rows affected)

-- SQL statement 82: Make all polygons right handed for zoomlevel: 7 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_7.STUnion(geom_7.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_7.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_7,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_7.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_nation_5m
), b AS (
	SELECT a.gid,
	       a.geom_7,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_nation_5m
   SET geom_7 = c.geom_7.ReorientObject()
  FROM cb_2014_us_nation_5m c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(0 rows affected)

-- SQL statement 83: Make all polygons right handed for zoomlevel: 8 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_8.STUnion(geom_8.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_8.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_8,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_8.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_nation_5m
), b AS (
	SELECT a.gid,
	       a.geom_8,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_nation_5m
   SET geom_8 = c.geom_8.ReorientObject()
  FROM cb_2014_us_nation_5m c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(0 rows affected)

-- SQL statement 84: Make all polygons right handed for zoomlevel: 9 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_9.STUnion(geom_9.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_9.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_9,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_nation_5m
), b AS (
	SELECT a.gid,
	       a.geom_9,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_nation_5m
   SET geom_9 = c.geom_9.ReorientObject()
  FROM cb_2014_us_nation_5m c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(0 rows affected)

--
-- Test Turf and DB areas agree to within 1%
--

--
-- Create spatial indexes
--

-- SQL statement 87: Index geometry column for zoomlevel: 6 >>>
CREATE SPATIAL INDEX cb_2014_us_nation_5m_geom_6_gix ON cb_2014_us_nation_5m (geom_6);


-- SQL statement 88: Index geometry column for zoomlevel: 7 >>>
CREATE SPATIAL INDEX cb_2014_us_nation_5m_geom_7_gix ON cb_2014_us_nation_5m (geom_7);


-- SQL statement 89: Index geometry column for zoomlevel: 8 >>>
CREATE SPATIAL INDEX cb_2014_us_nation_5m_geom_8_gix ON cb_2014_us_nation_5m (geom_8);


-- SQL statement 90: Index geometry column for zoomlevel: 9 >>>
CREATE SPATIAL INDEX cb_2014_us_nation_5m_geom_9_gix ON cb_2014_us_nation_5m (geom_9);


-- SQL statement 91: Index geometry column for original SRID geometry >>>
/*
 * SQL statement name: 	create_spatial_geometry_index.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:
 *						1: index name;e.g. geometry_cb_2014_us_500k_gix
 *						2: table name; e.g. geometry_cb_2014_us_500k
 *						3: Geometry field name; e.g. geom
 *						4: Xmin (4326); e.g. -179.13729006727
 *						5: Ymin (4326); e.g. -14.3737802873213
 *						6: Xmax (4326); e.g.  179.773803959804
 *						7: Ymax (4326); e.g. 71.352561
 *
 * Description:			Create geometry table
 * Note:				% becomes % after substitution
 */
CREATE SPATIAL INDEX cb_2014_us_nation_5m_geom_orig_gix ON cb_2014_us_nation_5m (geom_orig)
	WITH ( BOUNDING_BOX = (xmin=-179.148909, ymin=-14.548699000000001, xmax=179.77847, ymax=71.36516200000001));


--
-- Reports
--

-- SQL statement 93: Areas and centroids report >>>
/*
 * SQL statement name: 	area_centroid_report.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Area and centroids report
 * Note:				% becomes % after substitution
 */
WITH a AS (
	SELECT areaname, geom_9,
		   CAST(area_km2 AS NUMERIC(15,2)) AS area_km2,
		   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(15,2)) AS area_km2_calc,
		   CONCAT(
				CAST(CAST(geographic_centroid.Long AS NUMERIC(15,7)) AS VARCHAR(30)),
				',',
				CAST(CAST(geographic_centroid.Lat AS NUMERIC(15,7)) AS VARCHAR(30))
				) AS geographic_centroid,
		   CONCAT(
				CAST(CAST(geom_9.EnvelopeCenter().Long AS NUMERIC(15,7)) AS VARCHAR(30)),
				',',
				CAST(CAST(geom_9.EnvelopeCenter().Lat AS NUMERIC(15,7)) AS VARCHAR(30))
				) AS geographic_centroid_calc,
		   CAST((geom_9.EnvelopeCenter().STDistance(geographic_centroid))/1000 AS VARCHAR(30)) AS centroid_diff_km,
		   ROW_NUMBER() OVER (ORDER BY areaname) as nrow
	  FROM cb_2014_us_nation_5m
)
SELECT SUBSTRING(a.areaname, 1, 30) AS areaname,
       a.area_km2,
	   a.area_km2_calc,
	   CASE WHEN area_km2 = 0 THEN NULL
			ELSE CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(15,2))
			END AS pct_km2_diff,
	   a.geographic_centroid,
       a.geographic_centroid_calc,
	   a.centroid_diff_km
  FROM a
 WHERE nrow <= 100
 ORDER BY 1 ;

areaname                       area_km2          area_km2_calc     pct_km2_diff      geographic_centroid                                           geographic_centroid_calc                                      centroid_diff_km
------------------------------ ----------------- ----------------- ----------------- ------------------------------------------------------------- ------------------------------------------------------------- ------------------------------
United States                         9371410.00        9366617.08               .05 -108.5280837,45.1075717                                       -108.5847760,50.9802518                                       653.003

(1 rows affected)

-- SQL statement 94: Drop table cb_2014_us_state_500k >>>
IF OBJECT_ID('cb_2014_us_state_500k', 'U') IS NOT NULL DROP TABLE cb_2014_us_state_500k;


-- SQL statement 95: Create tablecb_2014_us_state_500k >>>
CREATE TABLE cb_2014_us_state_500k (
	statefp                        	NVARCHAR(1000) /* Current state Federal Information Processing Series (FIPS) code */,
	statens                        	NVARCHAR(1000) /* Current state Geographic Names Information System (GNIS) code */,
	affgeoid                       	NVARCHAR(1000) /* American FactFinder summary level code + geovariant code + ''00US'' + GEOID */,
	geoid                          	NVARCHAR(1000) /* State identifier; state FIPS code */,
	stusps                         	NVARCHAR(1000) /* Current United States Postal Service state abbreviation */,
	name                           	NVARCHAR(1000) /* Current State name */,
	lsad                           	NVARCHAR(1000) /* Current legal/statistical area description code for state */,
	aland                          	NVARCHAR(1000) /* Current land area (square meters) */,
	awater                         	NVARCHAR(1000) /* Current water area (square meters) */,
	gid                            	integer	NOT NULL /* Unique geographic index */,
	areaid                         	varchar(100)	NOT NULL /* Area ID (STATENS): Current state Geographic Names Information System (GNIS) code */,
	areaname                       	NVARCHAR(1000)	NOT NULL /* Area name (NAME): Current State name */,
	area_km2                       	numeric /* Area in square km */,
	geographic_centroid_wkt        	text /* Wellknown text for geographic centroid */,
	wkt_9                          	text /* Wellknown text for zoomlevel 9 */,
	wkt_8                          	text /* Wellknown text for zoomlevel 8 */,
	wkt_7                          	text /* Wellknown text for zoomlevel 7 */,
	wkt_6                          	text /* Wellknown text for zoomlevel 6 */);


-- SQL statement 96: Comment geospatial data table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'The State at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'The State at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k';


-- SQL statement 97: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'gid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Unique geographic index',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'gid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Unique geographic index',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'gid';


-- SQL statement 98: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'areaid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID (STATENS): Current state Geographic Names Information System (GNIS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'areaid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID (STATENS): Current state Geographic Names Information System (GNIS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'areaid';


-- SQL statement 99: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'areaname';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area name (NAME): Current State name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'areaname'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area name (NAME): Current State name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'areaname';


-- SQL statement 100: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'area_km2';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area in square km',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'area_km2'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area in square km',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'area_km2';


-- SQL statement 101: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'geographic_centroid_wkt';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'geographic_centroid_wkt'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'geographic_centroid_wkt';


-- SQL statement 102: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'wkt_6';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 6',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'wkt_6'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 6',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'wkt_6';


-- SQL statement 103: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'wkt_7';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 7',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'wkt_7'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 7',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'wkt_7';


-- SQL statement 104: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'wkt_8';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 8',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'wkt_8'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 8',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'wkt_8';


-- SQL statement 105: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'wkt_9';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 9',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'wkt_9'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Wellknown text for zoomlevel 9',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'wkt_9';


-- SQL statement 106: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'statefp';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current state Federal Information Processing Series (FIPS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'statefp'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current state Federal Information Processing Series (FIPS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'statefp';


-- SQL statement 107: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'statens';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current state Geographic Names Information System (GNIS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'statens'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current state Geographic Names Information System (GNIS) code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'statens';


-- SQL statement 108: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'affgeoid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'American FactFinder summary level code + geovariant code + ''00US'' + GEOID',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'affgeoid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'American FactFinder summary level code + geovariant code + ''00US'' + GEOID',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'affgeoid';


-- SQL statement 109: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'geoid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'State identifier; state FIPS code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'geoid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'State identifier; state FIPS code',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'geoid';


-- SQL statement 110: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'stusps';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current United States Postal Service state abbreviation',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'stusps'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current United States Postal Service state abbreviation',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'stusps';


-- SQL statement 111: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'name';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current State name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'name'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current State name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'name';


-- SQL statement 112: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'lsad';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current legal/statistical area description code for state',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'lsad'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current legal/statistical area description code for state',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'lsad';


-- SQL statement 113: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'aland';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current land area (square meters)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'aland'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current land area (square meters)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'aland';


-- SQL statement 114: Comment geospatial data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.cb_2014_us_state_500k';
SELECT @columnName  = 'awater';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Current water area (square meters)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'awater'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Current water area (square meters)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'awater';


-- SQL statement 115: Load table from CSV file >>>
BULK INSERT cb_2014_us_state_500k
FROM 'C:\Users\Peter\Documents\Work\usa\Tile maker USA/cb_2014_us_state_500k.csv'	-- Note use of pwd; set via -v pwd="%cd%" in the sqlcmd command line
WITH
(
	FORMATFILE = 'C:\Users\Peter\Documents\Work\usa\Tile maker USA/mssql_cb_2014_us_state_500k.fmt',		-- Use a format file
	TABLOCK					-- Table lock
);


(56 rows affected)

-- SQL statement 116: Row check: 56 >>>
DECLARE c1 CURSOR FOR SELECT COUNT(gid) AS total FROM cb_2014_us_state_500k;
/*
 * SQL statement name: 	csvfile_rowcheck.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: Expected number of rows; e.g. 3233
 *						3: Column to count; e.g. gid
 *
 * Description:			Check number of rows in loaded CSV file is as expected
 * Note:				%% becomes % after substitution
 */
DECLARE @c1_total AS int;
OPEN c1;
FETCH NEXT FROM c1 INTO @c1_total;
IF @c1_total = 56
	PRINT 'Table: cb_2014_us_state_500k row check OK: ' + CAST(@c1_total AS VARCHAR);
ELSE
	RAISERROR('Table: cb_2014_us_state_500k row check FAILED: expected: 56 got: %i', 16, 1, @c1_total);
CLOSE c1;
DEALLOCATE c1;;

Table: cb_2014_us_state_500k row check OK: 56

-- SQL statement 117: Add primary key cb_2014_us_state_500k >>>
ALTER TABLE cb_2014_us_state_500k ADD PRIMARY KEY (gid);


-- SQL statement 118: Add unique key cb_2014_us_state_500k >>>
/*
 * SQL statement name: 	add_unique_key.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. cb_2014_us_nation_5m
 *						2: constraint name; e.g. cb_2014_us_nation_5m_uk
 *						3: fields; e.g. areaid
 *
 * Description:			Add unique key constraint
 * Note:				%% becomes % after substitution
 */
ALTER TABLE cb_2014_us_state_500k ADD CONSTRAINT cb_2014_us_state_500k_uk UNIQUE(areaid);


--
-- Add geometric  data
--

-- SQL statement 120: Add geometry column: geographic centroid >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_state_500k ADD geographic_centroid geometry
 */
ALTER TABLE cb_2014_us_state_500k ADD geographic_centroid geography;


-- SQL statement 121: Add geometry column for original SRID geometry >>>
/*
 * SQL statement name: 	add_geometry_column2.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. geometry_cb_2014_us_500k
 *						2: column name; e.g. geom
 *						3: Column SRID; e.g. 4326 [NEVER USED IN SQL SERVER, set during WKT conversion]
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON [NEVER USED IN SQL SERVER]
 *                      5: Schema (rif_data. or "")
 *
 * Description:			Add *** geometry *** column to table
 * Note:				%% becomes % after substitution
 */
ALTER TABLE cb_2014_us_state_500k ADD geom_orig geometry;


-- SQL statement 122: Add geometry column for zoomlevel: 6 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_state_500k ADD geom_6 geometry
 */
ALTER TABLE cb_2014_us_state_500k ADD geom_6 geography;


-- SQL statement 123: Add geometry column for zoomlevel: 7 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_state_500k ADD geom_7 geometry
 */
ALTER TABLE cb_2014_us_state_500k ADD geom_7 geography;


-- SQL statement 124: Add geometry column for zoomlevel: 8 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_state_500k ADD geom_8 geometry
 */
ALTER TABLE cb_2014_us_state_500k ADD geom_8 geography;


-- SQL statement 125: Add geometry column for zoomlevel: 9 >>>
/*
 * SQL statement name: 	add_geometry_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. cb_2014_us_county_500k
 *						2: column name; e.g. geographic_centroid
 *						3: Column SRID; e.g. 4326
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON
 *
 * Description:			Add *** geography ***  column to table
 * Note:				%% becomes % after substitution
 *
 * May need to be swapped to geometry to be the same datatype as PostGIS (see: add_geometry_column2.sql):
 * ALTER TABLE cb_2014_us_state_500k ADD geom_9 geometry
 */
ALTER TABLE cb_2014_us_state_500k ADD geom_9 geography;


-- SQL statement 126: Update geographic centroid, geometry columns, handle polygons and mutlipolygons, convert highest zoomlevel to original SRID >>>
UPDATE cb_2014_us_state_500k
   SET geographic_centroid = geography::STGeomFromText(geographic_centroid_wkt, 4326),
       geom_6 = geography::STGeomFromText(wkt_6, 4326).MakeValid(),
       geom_7 = geography::STGeomFromText(wkt_7, 4326).MakeValid(),
       geom_8 = geography::STGeomFromText(wkt_8, 4326).MakeValid(),
       geom_9 = geography::STGeomFromText(wkt_9, 4326).MakeValid(),
       geom_orig = geometry::STGeomFromText(geometry::STGeomFromText(wkt_9, 4326).MakeValid().STAsText(), 4269);


(56 rows affected)

--
-- Test geometry and make valid if required
--

-- SQL statement 128: Check validity of geometry columns >>>
DECLARE c1 CURSOR FOR
SELECT areaname,
       6 AS geolevel,
       geom_6.IsValidDetailed() AS reason
  FROM cb_2014_us_state_500k
 WHERE geom_6.STIsValid() = 0
UNION
SELECT areaname,
       7 AS geolevel,
       geom_7.IsValidDetailed() AS reason
  FROM cb_2014_us_state_500k
 WHERE geom_7.STIsValid() = 0
UNION
SELECT areaname,
       8 AS geolevel,
       geom_8.IsValidDetailed() AS reason
  FROM cb_2014_us_state_500k
 WHERE geom_8.STIsValid() = 0
UNION
SELECT areaname,
       9 AS geolevel,
       geom_9.IsValidDetailed() AS reason
  FROM cb_2014_us_state_500k
 WHERE geom_9.STIsValid() = 0
ORDER BY 1, 2;
DECLARE @areaname AS VARCHAR(30);
DECLARE @geolevel AS int;
DECLARE @reason AS VARCHAR(90);
DECLARE @nrows AS int;
SET @nrows=0;
OPEN c1;
FETCH NEXT FROM c1 INTO @areaname, @geolevel, @reason;
WHILE @@FETCH_STATUS = 0
BEGIN
		SET @nrows+=1;
	    PRINT 'Area: ' + @areaname + ', geolevel: ' + CAST(@geolevel AS VARCHAR) + ': ' +RTRIM(@reason);
       FETCH NEXT FROM c1 INTO @areaname, @geolevel, @reason;
END
IF @nrows = 0
	PRINT 'Table: cb_2014_us_state_500k no invalid geometry check OK';
ELSE
	RAISERROR('Table: cb_2014_us_state_500k no invalid geometry check FAILED: %i invalid', 16, 1, @nrows);
CLOSE c1;
DEALLOCATE c1;

Table: cb_2014_us_state_500k no invalid geometry check OK

--
-- Make all polygons right handed
--

-- SQL statement 130: Make all polygons right handed for zoomlevel: 6 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_6.STUnion(geom_6.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_6.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_6,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_6.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_state_500k
), b AS (
	SELECT a.gid,
	       a.geom_6,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_state_500k
   SET geom_6 = c.geom_6.ReorientObject()
  FROM cb_2014_us_state_500k c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(24 rows affected)

-- SQL statement 131: Make all polygons right handed for zoomlevel: 7 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_7.STUnion(geom_7.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_7.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_7,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_7.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_state_500k
), b AS (
	SELECT a.gid,
	       a.geom_7,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_state_500k
   SET geom_7 = c.geom_7.ReorientObject()
  FROM cb_2014_us_state_500k c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(24 rows affected)

-- SQL statement 132: Make all polygons right handed for zoomlevel: 8 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_8.STUnion(geom_8.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_8.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_8,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_8.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_state_500k
), b AS (
	SELECT a.gid,
	       a.geom_8,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_state_500k
   SET geom_8 = c.geom_8.ReorientObject()
  FROM cb_2014_us_state_500k c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(24 rows affected)

-- SQL statement 133: Make all polygons right handed for zoomlevel: 9 >>>
/*
 * SQL statement name: 	force_rhr.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 * 						c.geom_9.STUnion(geom_9.STStartPoint()) is also possible from web comments, but DOES NOT work
 *						So always use c.geom_9.ReorientObject()
 */
WITH a AS (
	SELECT gid, geom_9,
		   CAST(area_km2 AS NUMERIC(21,6)) AS area_km2,
		   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(21,6)) AS area_km2_calc
	  FROM cb_2014_us_state_500k
), b AS (
	SELECT a.gid,
	       a.geom_9,
           a.area_km2,
	       a.area_km2_calc,
          CASE WHEN a.area_km2 > 0 THEN CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(21,6))
				WHEN a.area_km2 = a.area_km2_calc THEN 0
	        	ELSE NULL
	   	   END AS pct_km2_diff
  FROM a
)
UPDATE cb_2014_us_state_500k
   SET geom_9 = c.geom_9.ReorientObject()
  FROM cb_2014_us_state_500k c
 JOIN b ON b.gid = c.gid
 WHERE b.pct_km2_diff > 200 /* Threshold test */;


(22 rows affected)

--
-- Test Turf and DB areas agree to within 1%
--

--
-- Create spatial indexes
--

-- SQL statement 136: Index geometry column for zoomlevel: 6 >>>
CREATE SPATIAL INDEX cb_2014_us_state_500k_geom_6_gix ON cb_2014_us_state_500k (geom_6);


-- SQL statement 137: Index geometry column for zoomlevel: 7 >>>
CREATE SPATIAL INDEX cb_2014_us_state_500k_geom_7_gix ON cb_2014_us_state_500k (geom_7);


-- SQL statement 138: Index geometry column for zoomlevel: 8 >>>
CREATE SPATIAL INDEX cb_2014_us_state_500k_geom_8_gix ON cb_2014_us_state_500k (geom_8);


-- SQL statement 139: Index geometry column for zoomlevel: 9 >>>
CREATE SPATIAL INDEX cb_2014_us_state_500k_geom_9_gix ON cb_2014_us_state_500k (geom_9);


-- SQL statement 140: Index geometry column for original SRID geometry >>>
/*
 * SQL statement name: 	create_spatial_geometry_index.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:
 *						1: index name;e.g. geometry_cb_2014_us_500k_gix
 *						2: table name; e.g. geometry_cb_2014_us_500k
 *						3: Geometry field name; e.g. geom
 *						4: Xmin (4326); e.g. -179.13729006727
 *						5: Ymin (4326); e.g. -14.3737802873213
 *						6: Xmax (4326); e.g.  179.773803959804
 *						7: Ymax (4326); e.g. 71.352561
 *
 * Description:			Create geometry table
 * Note:				% becomes % after substitution
 */
CREATE SPATIAL INDEX cb_2014_us_state_500k_geom_orig_gix ON cb_2014_us_state_500k (geom_orig)
	WITH ( BOUNDING_BOX = (xmin=-179.148909, ymin=-14.548699000000001, xmax=179.77847, ymax=71.36516200000001));


--
-- Reports
--

-- SQL statement 142: Areas and centroids report >>>
/*
 * SQL statement name: 	area_centroid_report.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Area and centroids report
 * Note:				% becomes % after substitution
 */
WITH a AS (
	SELECT areaname, geom_9,
		   CAST(area_km2 AS NUMERIC(15,2)) AS area_km2,
		   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(15,2)) AS area_km2_calc,
		   CONCAT(
				CAST(CAST(geographic_centroid.Long AS NUMERIC(15,7)) AS VARCHAR(30)),
				',',
				CAST(CAST(geographic_centroid.Lat AS NUMERIC(15,7)) AS VARCHAR(30))
				) AS geographic_centroid,
		   CONCAT(
				CAST(CAST(geom_9.EnvelopeCenter().Long AS NUMERIC(15,7)) AS VARCHAR(30)),
				',',
				CAST(CAST(geom_9.EnvelopeCenter().Lat AS NUMERIC(15,7)) AS VARCHAR(30))
				) AS geographic_centroid_calc,
		   CAST((geom_9.EnvelopeCenter().STDistance(geographic_centroid))/1000 AS VARCHAR(30)) AS centroid_diff_km,
		   ROW_NUMBER() OVER (ORDER BY areaname) as nrow
	  FROM cb_2014_us_state_500k
)
SELECT SUBSTRING(a.areaname, 1, 30) AS areaname,
       a.area_km2,
	   a.area_km2_calc,
	   CASE WHEN area_km2 = 0 THEN NULL
			ELSE CAST(100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2) AS NUMERIC(15,2))
			END AS pct_km2_diff,
	   a.geographic_centroid,
       a.geographic_centroid_calc,
	   a.centroid_diff_km
  FROM a
 WHERE nrow <= 100
 ORDER BY 1 ;

areaname                       area_km2          area_km2_calc     pct_km2_diff      geographic_centroid                                           geographic_centroid_calc                                      centroid_diff_km
------------------------------ ----------------- ----------------- ----------------- ------------------------------------------------------------- ------------------------------------------------------------- ------------------------------
Alabama                                134272.00         133897.60               .28 -86.7664801,31.7690552                                        -86.7686828,31.7496785                                        2.15864
Alaska                                1516559.00        1522698.01               .40 -150.4186689,58.3829445                                       -151.4738059,59.1312166                                       103.327
American Samoa                            203.00            201.99               .50 -170.3028174,-14.2005732                                      -170.2959930,-14.1991422                                      0.753457
Arizona                                295964.00         295235.53               .25 -113.3962308,34.4586965                                       -113.4473011,34.4482863                                       4.8329
Arkansas                               138054.00         137732.71               .23 -91.7460601,34.7989664                                        -91.7355145,34.8078319                                        1.37786
California                             410633.00         409888.03               .18 -120.2495103,36.2457149                                       -120.1715860,36.2816155                                       8.05633
Colorado                               269980.00         269600.61               .14 -104.8083807,38.9255584                                       -104.8244214,38.9644696                                       4.53803
Commonwealth of the Northern M            480.00            477.74               .47 145.6158196,16.1727270                                        145.6146566,16.1800355                                        0.818271
Connecticut                             12941.00          12930.94               .08 -72.8528547,41.3456700                                        -72.8534926,41.3426830                                        0.336014
Delaware                                 5247.00           5239.95               .13 -75.4994397,39.2171211                                        -75.4955681,39.2266829                                        1.11296
District of Columbia                      177.00            176.97               .02 -77.0161157,38.8992875                                        -77.0183130,38.8981127                                        0.230967
Florida                                151512.00         150962.67               .36 -82.1912856,27.2641345                                        -82.1547044,27.2680062                                        3.6476
Georgia                                153017.00         152586.97               .28 -82.8985468,32.6450261                                        -82.8777461,32.6467765                                        1.96125
Guam                                      564.00            560.58               .61 144.7632529,13.4279676                                        144.7652779,13.4278028                                        0.220051
Hawaii                                  16836.00          16749.69               .51 -157.7523478,21.0611975                                       -157.7165084,21.0922908                                       5.07169
Idaho                                  216480.00         216445.19               .02 -114.6750465,45.4195058                                       -114.6603165,45.4457501                                       3.13628
Illinois                               146089.00         145919.05               .12 -89.2220210,39.8410669                                        -89.2258648,39.8229279                                        2.0407
Indiana                                 93835.00          93722.30               .12 -86.6396086,39.2583984                                        -86.6655253,39.2257279                                        4.26165
Iowa                                   145844.00         145742.34               .07 -93.8227667,42.0221135                                        -93.8151855,42.0375233                                        1.82314
Kansas                                 213421.00         213096.15               .15 -96.9603123,38.7478453                                        -96.9901974,38.7814421                                        4.54495
Kentucky                               104842.00         104658.47               .18 -85.2123467,37.7223858                                        -85.2068848,37.7528177                                        3.41182
Louisiana                              122527.00         122142.32               .31 -91.2369599,30.3596078                                        -91.2231357,30.3595940                                        1.32902
Maine                                   84895.00          84901.80               .01 -68.9047269,44.5331050                                        -68.9047529,44.5405675                                        0.829256
Maryland                                26683.00          26646.73               .14 -76.5695403,38.7769268                                        -76.5711298,38.7808231                                        0.454047
Massachusetts                           21269.00          21255.42               .06 -70.8496779,41.9574786                                        -70.8400672,41.9560536                                        0.81236
Michigan                               151073.00         151047.18               .02 -85.7125401,45.4651011                                        -85.6891882,45.4935603                                        3.65213
Minnesota                              218495.00         218557.53               .03 -94.2946076,46.9142549                                        -94.2953285,46.9645226                                        5.58851
Mississippi                            123841.00         123495.21               .28 -90.2098739,32.2488404                                        -90.2138270,32.2474982                                        0.401164
Missouri                               180826.00         180544.22               .16 -92.1883047,38.3681761                                        -92.1247204,38.3985600                                        6.4992
Montana                                380654.00         380831.58               .05 -112.4401590,46.0953789                                       -112.4705830,46.1396785                                       5.45684
Nebraska                               200500.00         200334.43               .08 -97.8496887,41.4426956                                        -97.8269072,41.4787766                                        4.4363
Nevada                                 286755.00         286372.77               .13 -115.9924743,37.9127710                                       -115.9484724,37.9198649                                       3.94849
New Hampshire                           24046.00          24038.51               .03 -71.5978177,43.9585841                                        -71.6047671,43.9759756                                        2.01126
New Jersey                              20173.00          20150.47               .11 -74.7342061,40.1862212                                        -74.7408285,40.1865817                                        0.565389
New Mexico                             315687.00         314916.83               .24 -106.2103196,34.0796842                                       -106.1825525,34.0729228                                       2.67045
New York                               127049.00         126986.52               .05 -74.9314132,42.2529504                                        -74.9379043,42.2959822                                        4.80981
North Carolina                         128880.00         128599.17               .22 -78.1838148,35.4144296                                        -78.1563061,35.4463276                                        4.33183
North Dakota                           183006.00         183108.85               .06 -97.7974493,47.3592469                                        -97.7792002,47.3868257                                        3.36168
Ohio                                   107014.00         106894.42               .11 -82.4309673,40.3798732                                        -82.4276760,40.3791238                                        0.291615
Oklahoma                               181432.00         181035.08               .22 -97.1409457,34.7124801                                        -97.1156299,34.6980422                                        2.81859
Oregon                                 251404.00         251335.95               .03 -121.2656820,44.5161241                                       -121.2772822,44.5591170                                       4.86565
Pennsylvania                           117458.00         117343.70               .10 -76.8260790,40.9801819                                        -76.7794707,41.0156052                                        5.55463
Puerto Rico                              9079.00           9029.78               .54 -66.2423901,18.2032215                                        -66.2428670,18.2045412                                        0.154535
Rhode Island                             2849.00           2846.23               .10 -71.3998546,41.5702071                                        -71.4007167,41.5661906                                        0.451852
South Carolina                          80795.00          80589.34               .25 -81.3588011,33.5808271                                        -81.3627012,33.5789162                                        0.419542
South Dakota                           199757.00         199726.92               .02 -98.1393053,43.8929745                                        -98.0953026,43.9005429                                        3.63403
Tennessee                              109382.00         109150.38               .21 -85.8408130,35.8337160                                        -85.8306774,35.8777864                                        4.97486
Texas                                  689860.00         687753.43               .31 -98.7725069,29.8219671                                        -98.7743170,29.8607031                                        4.29744
United States Virgin Islands              358.00            355.95               .57 -64.8355293,18.1760173                                        -64.8366418,18.1743775                                        0.216319
Utah                                   220179.00         219881.37               .14 -111.6210016,39.1152289                                       -111.6250827,39.1682195                                       5.89349
Vermont                                 24908.00          24902.41               .02 -72.4362711,44.0669831                                        -72.4375341,44.0707847                                        0.434359
Virginia                               105026.00         104842.89               .17 -78.0541807,37.6982304                                        -78.0415529,37.7255208                                        3.22716
Washington                             175346.00         175443.54               .06 -122.6400069,47.7959450                                       -122.6429274,47.8063193                                       1.17404
West Virginia                           62848.00          62753.77               .15 -80.3551374,38.7506277                                        -80.3661753,38.7528631                                        0.991077
Wisconsin                              145379.00         145364.17               .01 -89.5095248,45.1986448                                        -89.4984439,45.2246008                                        3.01311
Wyoming                                253458.00         253335.86               .05 -107.5718275,42.9599050                                       -107.5472209,42.9935163                                       4.23925

(56 rows affected)

--
-- Geography meta data
--

--
-- Drop dependent objects: tiles view and generate_series() [MS SQL Server only]
--

-- SQL statement 145: Drop generate_series() function >>>
/*
 * SQL statement name: 	drop_generate_series.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:			None
 * Description:			Drop generate_series() function (TF = SQL table-valued-function)
 */
IF OBJECT_ID (N'generate_series', N'TF') IS NOT NULL
    DROP FUNCTION generate_series;  ;


-- SQL statement 146: Drop dependent object - view tiles_usa_2014 >>>
IF OBJECT_ID('tiles_usa_2014', 'V') IS NOT NULL DROP VIEW tiles_usa_2014;


-- SQL statement 147: Drop dependent object - FK table geolevels_usa_2014 >>>
IF OBJECT_ID('geolevels_usa_2014', 'U') IS NOT NULL DROP TABLE geolevels_usa_2014;


-- SQL statement 148: Drop table geography_usa_2014 >>>
IF OBJECT_ID('geography_usa_2014', 'U') IS NOT NULL DROP TABLE geography_usa_2014;


-- SQL statement 149: Create generate_series() function >>>
/*
 * SQL statement name: 	generate_series.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:			None
 * Description:			Generate a series of values, from start to stop with a step size of step
 *						Original by: Simon Greener, Independent GeoSpatial Solutions Architect
 *						http://www.spatialdbadvisor.com/sql_server_blog/86/generate_series-for-sql-server-2008
 */
CREATE FUNCTION generate_series ( @p_start INT, @p_end INT, @p_step INT=1 )
RETURNS @Integers TABLE ( [IntValue] INT )
AS
BEGIN
    DECLARE
      @v_i                 INT,
      @v_step              INT,
      @v_terminating_value INT;
    BEGIN
      SET @v_i = CASE WHEN @p_start IS NULL THEN 1 ELSE @p_start END;
      SET @v_step  = CASE WHEN @p_step IS NULL OR @p_step = 0 THEN 1 ELSE @p_step END;
      SET @v_terminating_value =  @p_start + CONVERT(INT,ABS(@p_start-@p_end) / ABS(@v_step) ) * @v_step;
      -- Check for impossible combinations
      IF NOT ( ( @p_start > @p_end AND SIGN(@p_step) = 1 )
               OR
               ( @p_start < @p_end AND SIGN(@p_step) = -1 ))
      BEGIN
        -- Generate values
        WHILE ( 1 = 1 )
        BEGIN
           INSERT INTO @Integers ( [IntValue] ) VALUES ( @v_i )
           IF ( @v_i = @v_terminating_value )
              BREAK
           SET @v_i = @v_i + @v_step;
        END;
      END;
    END;
    RETURN
END;


-- SQL statement 150: Create geography meta data table >>>
/*
 * SQL statement name: 	create_geography_table.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: geography table; e.g. geography_cb_2014_us_county_500k
 *
 * Description:			Create geography table compatible with RIF40_GEOGRAPHIES
 *
 *		CREATE TABLE rif40_geographies
 *		(
 *		  geography character varying(50) NOT NULL, -- Geography name
 *		  description character varying(250) NOT NULL, -- Description
 *		  hierarchytable character varying(30) NOT NULL, -- Hierarchy table
 *		  tiletable character varying(30) NOT NULL, -- Tile table
 *		  adjacencytable character varying(30) NOT NULL, -- Adjacency table
 *		  geometrytable character varying(30) NOT NULL, -- Geometry table
 *		  srid integer DEFAULT 0, -- Postgres projection SRID
 *		  defaultcomparea character varying(30), -- Default comparison area
 *		  defaultstudyarea character varying(30), -- Default study area
 *		  postal_population_table character varying(30), -- Postal population table. Table of postal points (e.g. postcodes, ZIP codes); geolevels; X and YCOORDINATES (in projection SRID); male, female and total populations. Converted to SRID points by loader [not in 4326 Web Mercator lat/long]. Used in creating population wieght centroids and in converting postal points to geolevels. Expected columns &lt;postal_point_column&gt;, XCOORDINATE, YCOORDINATE, 1+ &lt;GEOLEVEL_NAME&gt;, MALES, FEMALES, TOTAL
 *		  postal_point_column character varying(30), -- Column name for postal points (e.g. POSTCODE, ZIP_CODE)
 *		  partition smallint DEFAULT 0, -- Enable partitioning. Extract tables will be partition if the number of years >= 2x the RIF40_PARAMETERS parameters Parallelisation [which has a default of 4, so extracts covering 8 years or more will be partitioned].
 *		  max_geojson_digits smallint DEFAULT 8, -- Max digits in ST_AsGeoJson() [optimises file size by removing unecessary precision, the default value of 8 is normally fine.]
 *		  CONSTRAINT rif40_geographies_pk PRIMARY KEY (geography),
 *		  CONSTRAINT partition_ck CHECK (partition = ANY (ARRAY[0, 1])),
 *		  CONSTRAINT postal_population_table_ck CHECK (postal_population_table IS NOT NULL AND postal_point_column IS NOT NULL OR postal_population_table IS NULL AND postal_point_column IS NULL)
 *		)
 *
 * Note:				%% becomes % after substitution
 */
CREATE TABLE geography_usa_2014 (
       geography               VARCHAR(50)  NOT NULL,
       description             VARCHAR(250) NOT NULL,
       hierarchytable          VARCHAR(30)  NOT NULL,
       geometrytable           VARCHAR(30)  NOT NULL,
       tiletable               VARCHAR(30)  NOT NULL,			/* New for DB */
	   adjacencytable 		   VARCHAR(30) NOT NULL,			/* New for DB */
       srid                    INTEGER      NOT NULL DEFAULT 0,
       defaultcomparea         VARCHAR(30)  NULL,
       defaultstudyarea        VARCHAR(30)  NULL,
       minzoomlevel       	   INTEGER      NOT NULL DEFAULT 6,  /* New for DB */
       maxzoomlevel       	   INTEGER      NOT NULL DEFAULT 11, /* New for DB */
       postal_population_table VARCHAR(30)  NULL,
       postal_point_column 	   VARCHAR(30)  NULL,
       partition 			   INTEGER      NOT NULL DEFAULT 0,
       max_geojson_digits 	   INTEGER      NOT NULL DEFAULT 8,
       CONSTRAINT geography_usa_2014_pk PRIMARY KEY(geography),
	   CONSTRAINT geography_usa_2014_part_ck CHECK (partition IN (0, 1)),
	   CONSTRAINT geography_usa_2014_ppt_ck CHECK (
			postal_population_table IS NOT NULL AND postal_point_column IS NOT NULL OR postal_population_table IS NULL AND postal_point_column IS NULL)
	);


-- SQL statement 151: Comment geography meta data table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchial geographies. Usually based on Census geography',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchial geographies. Usually based on Census geography',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014';


-- SQL statement 152: Populate geography meta data table >>>
/*
 * SQL statement name: 	insert_geography.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. GEOGRAPHY_CB_2014_US_COUNTY_500K
 *						2: geography; e.g. CB_2014_US_500K
 *						3: geography description; e.g. United states to county level
 *						4: hierarchytable; e.g. HIERARCHY_CB_2014_US_500K
 *						5: geometrytable; e.g. GEOMETRY_CB_2014_US_500K
 *						6: tiletable; e.g. TILES_CB_2014_US_500K
 * 						7: SRID; e.g. 4269
 *						8: Default comparision area, e.g. GEOID
 *						9: Default study area, e.g. STATENS
 *						10: Min zoomlevel
 *						11: Max zoomlevel
 *           			12: Postal population table (quote enclosed or NULL)
 *      				13: Postal point column (quote enclosed or NULL)
 *						14: Partition (0/1)
 *						15: Max geojson digits
 *						16: adjacencytable; e.g. ADJACENCY_CB_2014_US_500K
 *
 * Description:			Insert into geography table
 * Note:				%% becomes % after substitution
 */
INSERT INTO geography_usa_2014 (
geography, description, hierarchytable, geometrytable, tiletable, adjacencytable, srid, defaultcomparea, defaultstudyarea, minzoomlevel, maxzoomlevel,
		postal_population_table, postal_point_column, partition, max_geojson_digits)
SELECT 'USA_2014' AS geography,
       'US 2014 Census geography to county level' AS description,
       'HIERARCHY_USA_2014' AS hierarchytable,
	   'GEOMETRY_USA_2014' AS geometrytable,
	   'TILES_USA_2014' AS tiletable,
	   'ADJACENCY_USA_2014' AS adjacencytable,
       4269   AS srid,
       NULL AS defaultcomparea,	/* See: update_geography.sql */
       NULL AS defaultstudyarea,
	   6  AS minzoomlevel,
	   9  AS maxzoomlevel,
	   NULL  AS postal_population_table,
       NULL  AS postal_point_column,
       0  AS partition,
       6  AS max_geojson_digits;


(1 rows affected)

-- SQL statement 153: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'geography';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geography name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'geography'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geography name',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'geography';


-- SQL statement 154: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'description';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Description',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'description'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Description',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'description';


-- SQL statement 155: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'hierarchytable';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'hierarchytable'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'hierarchytable';


-- SQL statement 156: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'geometrytable';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geometry table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'geometrytable'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geometry table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'geometrytable';


-- SQL statement 157: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'tiletable';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Tile table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'tiletable'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Tile table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'tiletable';


-- SQL statement 158: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'srid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Projection SRID',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'srid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Projection SRID',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'srid';


-- SQL statement 159: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'defaultcomparea';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Default comparison area: lowest resolution geolevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'defaultcomparea'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Default comparison area: lowest resolution geolevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'defaultcomparea';


-- SQL statement 160: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'defaultstudyarea';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Default study area: highest resolution geolevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'defaultstudyarea'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Default study area: highest resolution geolevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'defaultstudyarea';


-- SQL statement 161: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'minzoomlevel';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Min zoomlevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'minzoomlevel'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Min zoomlevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'minzoomlevel';


-- SQL statement 162: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'maxzoomlevel';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Max zoomlevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'maxzoomlevel'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Max zoomlevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'maxzoomlevel';


-- SQL statement 163: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'postal_population_table';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Postal_population_table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'postal_population_table'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Postal_population_table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'postal_population_table';


-- SQL statement 164: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'postal_point_column';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Postal_point_column',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'postal_point_column'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Postal_point_column',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'postal_point_column';


-- SQL statement 165: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'partition';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Partition geometry and tile tables (0/1)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'partition'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Partition geometry and tile tables (0/1)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'partition';


-- SQL statement 166: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'max_geojson_digits';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Maximum digits in geojson (topojson quantisation)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'max_geojson_digits'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Maximum digits in geojson (topojson quantisation)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'max_geojson_digits';


-- SQL statement 167: Comment geography meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geography_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geography_usa_2014';
SELECT @columnName  = 'adjacencytable';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Adjacency table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'adjacencytable'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Adjacency table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geography_usa_2014',
		@level2type = N'Column', @level2name = 'adjacencytable';


--
-- Geolevels meta data
--

-- SQL statement 169: Create geolevels meta data table >>>
/*
 * SQL statement name: 	create_geolevels_table.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: geolevels table; e.g. geolevels_cb_2014_us_county_500k
 *						2: geography table; e.g. geography_cb_2014_us_county_500k
 *
 * Description:			Create geography table compatible with RIF40_GEOGRAPHIES
 *
 *	CREATE TABLE t_rif40_geolevels
 *	(
 *	  geography character varying(50) NOT NULL, -- Geography (e.g EW2001)
 *	  geolevel_name character varying(30) NOT NULL, -- Name of geolevel. This will be a column name in the numerator/denominator tables
 *	  geolevel_id smallint NOT NULL, -- ID for ordering (1=lowest resolution). Up to 99 supported.
 *	  description character varying(250) NOT NULL, -- Description
 *	  lookup_table character varying(30) NOT NULL, -- Lookup table name. This is used to translate codes to the common names, e.g a LADUA of 00BK is &quot;Westminster&quot;
 *	  lookup_desc_column character varying(30) NOT NULL, -- Lookup table description column name.
 *	  centroidxcoordinate_column character varying(30), -- Lookup table centroid X co-ordinate column name. Can also use CENTROIDSFILE instead.
 *	  centroidycoordinate_column character varying(30), -- Lookup table centroid Y co-ordinate column name.
 *	  shapefile character varying(512), -- Location of the GIS shape file. NULL if PostGress/PostGIS used. Can also use SHAPEFILE_GEOMETRY instead,
 *	  centroidsfile character varying(512), -- Location of the GIS centroids file. Can also use CENTROIDXCOORDINATE_COLUMN, CENTROIDYCOORDINATE_COLUMN instead.
 *	  shapefile_table character varying(30), -- Table containing GIS shape file data (created using shp2pgsql).
 *	  shapefile_area_id_column character varying(30), -- Column containing the AREA_IDs in SHAPEFILE_TABLE
 *	  shapefile_desc_column character varying(30), -- Column containing the AREA_ID descriptions in SHAPEFILE_TABLE
 *	  centroids_table character varying(30), -- Table containing GIS shape file data with Arc GIS calculated population weighted centroids (created using shp2pgsql). PostGIS does not support population weighted centroids.
 *	  centroids_area_id_column character varying(30), -- Column containing the AREA_IDs in CENTROIDS_TABLE. X and Y co-ordinates ciolumns are asummed to be named after CENTROIDXCOORDINATE_COLUMN and CENTROIDYCOORDINATE_COLUMN.
 *	  covariate_table character varying(30), -- Name of table used for covariates at this geolevel
 *	  restricted smallint DEFAULT 0, -- Is geolevel access rectricted by Inforamtion Governance restrictions (0/1). If 1 (Yes) then a) students cannot access this geolevel and b) if the system parameter ExtractControl=1 then the user must be granted permission by a RIF_MANAGER to extract from the database the results, data extract and maps tables. This is enforced by the RIF application.
 *	  resolution smallint NOT NULL, -- Can use a map for selection at this resolution (0/1)
 *	  comparea smallint NOT NULL, -- Able to be used as a comparison area (0/1)
 *	  listing smallint NOT NULL, -- Able to be used in a disease map listing (0/1)
 *	  CONSTRAINT t_rif40_geolevels_pk PRIMARY KEY (geography, geolevel_name),
 *	  CONSTRAINT t_rif40_geol_comparea_ck CHECK (comparea IN (0, 1)),
 *	  CONSTRAINT t_rif40_geol_listing_ck CHECK (listing iN (0, 1)),
 *	  CONSTRAINT t_rif40_geol_resolution_ck CHECK (resolution IN (0, 1)),
 *	  CONSTRAINT t_rif40_geol_restricted_ck CHECK (restricted IN (0, 1))
 *	)
 *
 * Note:				%% becomes % after substitution
*/
CREATE TABLE geolevels_usa_2014 (
       geography                       VARCHAR(50)  NOT NULL,
       geolevel_name                   VARCHAR(30)  NOT NULL,
       geolevel_id			           INTEGER	    NOT NULL,
       description                     VARCHAR(250) NOT NULL,
       lookup_table                    VARCHAR(30)  NOT NULL,
       lookup_desc_column              VARCHAR(30)  NOT NULL,
       shapefile                       VARCHAR(512) NOT NULL,
       shapefile_table                 VARCHAR(30)  NULL,
       shapefile_area_id_column        VARCHAR(30)  NOT NULL,
       shapefile_desc_column           VARCHAR(30)  NULL,
	   centroids_table 				   VARCHAR(30)  NULL,
	   centroids_area_id_column 	   VARCHAR(30)  NULL,
	   covariate_table 				   VARCHAR(30)  NULL,
       restricted 					   INTEGER      NULL DEFAULT 0,
       resolution                      INTEGER      NULL,
       comparea                        INTEGER      NULL,
       listing                         INTEGER      NULL,
	   areaid_count 				   INTEGER      NULL,
       CONSTRAINT geolevels_usa_2014_pk PRIMARY KEY(geography, geolevel_name),
	   CONSTRAINT geolevels_usa_2014_fk FOREIGN KEY (geography)
			REFERENCES geography_usa_2014 (geography),
	   CONSTRAINT geolevels_usa_2014_comparea_ck CHECK (comparea IN (0, 1)),
	   CONSTRAINT geolevels_usa_2014_listing_ck CHECK (listing iN (0, 1)),
	   CONSTRAINT geolevels_usa_2014_resolution_ck CHECK (resolution IN (0, 1)),
	   CONSTRAINT geolevels_usa_2014_restricted_ck CHECK (restricted IN (0, 1))
);


-- SQL statement 170: Comment geolevels meta data table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geolevels: hierarchy of level within a geography',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geolevels: hierarchy of level within a geography',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014';


-- SQL statement 171: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'geography';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geography (e.g EW2001)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'geography'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geography (e.g EW2001)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'geography';


-- SQL statement 172: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'geolevel_name';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Name of geolevel. This will be a column name in the numerator/denominator tables',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_name'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Name of geolevel. This will be a column name in the numerator/denominator tables',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_name';


-- SQL statement 173: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'geolevel_id';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id';


-- SQL statement 174: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'description';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Description',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'description'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Description',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'description';


-- SQL statement 175: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'lookup_table';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table name. This is used to translate codes to the common names, e.g a LADUA of 00BK is "Westminster"',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'lookup_table'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table name. This is used to translate codes to the common names, e.g a LADUA of 00BK is "Westminster"',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'lookup_table';


-- SQL statement 176: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'lookup_desc_column';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table description column name.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'lookup_desc_column'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table description column name.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'lookup_desc_column';


-- SQL statement 177: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'shapefile';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Location of the GIS shape file. NULL if PostGress/PostGIS used. Can also use SHAPEFILE_GEOMETRY instead',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'shapefile'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Location of the GIS shape file. NULL if PostGress/PostGIS used. Can also use SHAPEFILE_GEOMETRY instead',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'shapefile';


-- SQL statement 178: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'shapefile_table';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Table containing GIS shape file data.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'shapefile_table'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Table containing GIS shape file data.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'shapefile_table';


-- SQL statement 179: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'shapefile_area_id_column';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Column containing the AREA_IDs in SHAPEFILE_TABLE',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'shapefile_area_id_column'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Column containing the AREA_IDs in SHAPEFILE_TABLE',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'shapefile_area_id_column';


-- SQL statement 180: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'shapefile_desc_column';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Column containing the AREA_ID descriptions in SHAPEFILE_TABLE',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'shapefile_desc_column'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Column containing the AREA_ID descriptions in SHAPEFILE_TABLE',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'shapefile_desc_column';


-- SQL statement 181: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'resolution';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Can use a map for selection at this resolution (0/1)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'resolution'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Can use a map for selection at this resolution (0/1)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'resolution';


-- SQL statement 182: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'comparea';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Able to be used as a comparison area (0/1)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'comparea'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Able to be used as a comparison area (0/1)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'comparea';


-- SQL statement 183: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'listing';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Able to be used in a disease map listing (0/1)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'listing'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Able to be used in a disease map listing (0/1)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'listing';


-- SQL statement 184: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'areaid_count';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Total number of area IDs within the geolevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'areaid_count'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Total number of area IDs within the geolevel',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'areaid_count';


-- SQL statement 185: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'centroids_table';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Centroids table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'centroids_table'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Centroids table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'centroids_table';


-- SQL statement 186: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'centroids_area_id_column';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Centroids area id column',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'centroids_area_id_column'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Centroids area id column',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'centroids_area_id_column';


-- SQL statement 187: Comment geolevels meta data column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geolevels_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geolevels_usa_2014';
SELECT @columnName  = 'covariate_table';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Covariate table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'covariate_table'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Covariate table',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geolevels_usa_2014',
		@level2type = N'Column', @level2name = 'covariate_table';


-- SQL statement 188: Insert geolevels meta data for: cb_2014_us_nation_5m >>>
/*
 * SQL statement name: 	insert_geolevel.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. GEOLEVELS_CB_2014_US_COUNTY_500K
 *						2: geography; e.g. CB_2014_US_500K
 *						3: Geolevel name; e.g. CB_2014_US_COUNTY_500K
 *						4: Geolevel id; e.g. 3
 *						5: Geolevel description; e.g. "The State-County at a scale of 1:500,000"
 *						6: lookup table; e.g. LOOKUP_CB_2014_US_COUNTY_500K
 * 						7: shapefile; e.g. cb_2014_us_county_500k.shp
 *						8: shapefile table; e.g. CB_2014_US_COUNTY_500K
 *						9: covariate_table; e.g. CB_2014_US_500K_COVARIATES_CB_2014_US_COUNTY_500K
 *						10: shapefile_area_id_column; e.g. COUNTYNS
 *						11: shapefile_desc_column; e.g. NAME
 * 						12: lookup_desc_column; e.g. AREANAME
 *						13: resolution: Can use a map for selection at this resolution (0/1)
 *						14: comparea: Able to be used as a comparison area (0/1)
 *						15: listing: Able to be used in a disease map listing (0/1)
 *
 * Description:			Insert into geography table
 * Note:				%% becomes % after substitution
 */
INSERT INTO geolevels_usa_2014 (
   geography, geolevel_name, geolevel_id, description, lookup_table,
   lookup_desc_column, shapefile, shapefile_table, shapefile_area_id_column, shapefile_desc_column,
   resolution, comparea, listing, covariate_table)
SELECT 'USA_2014' AS geography,
       'CB_2014_US_NATION_5M' AS geolevel_name,
       1 AS geolevel_id,
       'The nation at a scale of 1:5,000,000' AS description,
       'LOOKUP_CB_2014_US_NATION_5M' AS lookup_table,
       'AREANAME' AS lookup_desc_column,
       'cb_2014_us_nation_5m.shp' AS shapefile,
       'CB_2014_US_NATION_5M' AS shapefile_table,
       'GEOID' AS shapefile_area_id_column,
       'NAME' AS shapefile_desc_column,
       1 AS resolution,
       1 AS comparea,
       1 AS listing,
	   NULL AS covariate_table;


(1 rows affected)

-- SQL statement 189: Insert geolevels meta data for: cb_2014_us_state_500k >>>
/*
 * SQL statement name: 	insert_geolevel.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. GEOLEVELS_CB_2014_US_COUNTY_500K
 *						2: geography; e.g. CB_2014_US_500K
 *						3: Geolevel name; e.g. CB_2014_US_COUNTY_500K
 *						4: Geolevel id; e.g. 3
 *						5: Geolevel description; e.g. "The State-County at a scale of 1:500,000"
 *						6: lookup table; e.g. LOOKUP_CB_2014_US_COUNTY_500K
 * 						7: shapefile; e.g. cb_2014_us_county_500k.shp
 *						8: shapefile table; e.g. CB_2014_US_COUNTY_500K
 *						9: covariate_table; e.g. CB_2014_US_500K_COVARIATES_CB_2014_US_COUNTY_500K
 *						10: shapefile_area_id_column; e.g. COUNTYNS
 *						11: shapefile_desc_column; e.g. NAME
 * 						12: lookup_desc_column; e.g. AREANAME
 *						13: resolution: Can use a map for selection at this resolution (0/1)
 *						14: comparea: Able to be used as a comparison area (0/1)
 *						15: listing: Able to be used in a disease map listing (0/1)
 *
 * Description:			Insert into geography table
 * Note:				%% becomes % after substitution
 */
INSERT INTO geolevels_usa_2014 (
   geography, geolevel_name, geolevel_id, description, lookup_table,
   lookup_desc_column, shapefile, shapefile_table, shapefile_area_id_column, shapefile_desc_column,
   resolution, comparea, listing, covariate_table)
SELECT 'USA_2014' AS geography,
       'CB_2014_US_STATE_500K' AS geolevel_name,
       2 AS geolevel_id,
       'The State at a scale of 1:500,000' AS description,
       'LOOKUP_CB_2014_US_STATE_500K' AS lookup_table,
       'AREANAME' AS lookup_desc_column,
       'cb_2014_us_state_500k.shp' AS shapefile,
       'CB_2014_US_STATE_500K' AS shapefile_table,
       'STATENS' AS shapefile_area_id_column,
       'NAME' AS shapefile_desc_column,
       1 AS resolution,
       1 AS comparea,
       1 AS listing,
	   'COV_CB_2014_US_STATE_500K' AS covariate_table;


(1 rows affected)

-- SQL statement 190: Insert geolevels meta data for: cb_2014_us_county_500k >>>
/*
 * SQL statement name: 	insert_geolevel.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. GEOLEVELS_CB_2014_US_COUNTY_500K
 *						2: geography; e.g. CB_2014_US_500K
 *						3: Geolevel name; e.g. CB_2014_US_COUNTY_500K
 *						4: Geolevel id; e.g. 3
 *						5: Geolevel description; e.g. "The State-County at a scale of 1:500,000"
 *						6: lookup table; e.g. LOOKUP_CB_2014_US_COUNTY_500K
 * 						7: shapefile; e.g. cb_2014_us_county_500k.shp
 *						8: shapefile table; e.g. CB_2014_US_COUNTY_500K
 *						9: covariate_table; e.g. CB_2014_US_500K_COVARIATES_CB_2014_US_COUNTY_500K
 *						10: shapefile_area_id_column; e.g. COUNTYNS
 *						11: shapefile_desc_column; e.g. NAME
 * 						12: lookup_desc_column; e.g. AREANAME
 *						13: resolution: Can use a map for selection at this resolution (0/1)
 *						14: comparea: Able to be used as a comparison area (0/1)
 *						15: listing: Able to be used in a disease map listing (0/1)
 *
 * Description:			Insert into geography table
 * Note:				%% becomes % after substitution
 */
INSERT INTO geolevels_usa_2014 (
   geography, geolevel_name, geolevel_id, description, lookup_table,
   lookup_desc_column, shapefile, shapefile_table, shapefile_area_id_column, shapefile_desc_column,
   resolution, comparea, listing, covariate_table)
SELECT 'USA_2014' AS geography,
       'CB_2014_US_COUNTY_500K' AS geolevel_name,
       3 AS geolevel_id,
       'The County at a scale of 1:500,000' AS description,
       'LOOKUP_CB_2014_US_COUNTY_500K' AS lookup_table,
       'AREANAME' AS lookup_desc_column,
       'cb_2014_us_county_500k.shp' AS shapefile,
       'CB_2014_US_COUNTY_500K' AS shapefile_table,
       'COUNTYNS' AS shapefile_area_id_column,
       'NAME' AS shapefile_desc_column,
       1 AS resolution,
       1 AS comparea,
       1 AS listing,
	   'COV_CB_2014_US_COUNTY_500K' AS covariate_table;


(1 rows affected)

--
-- Create Geolevels lookup tables
--

-- SQL statement 192: Drop table lookup_cb_2014_us_nation_5m >>>
IF OBJECT_ID('lookup_cb_2014_us_nation_5m', 'U') IS NOT NULL DROP TABLE lookup_cb_2014_us_nation_5m;


-- SQL statement 193: Create table lookup_cb_2014_us_nation_5m >>>
/*
 * SQL statement name: 	create_lookup_table.sql
 * Type:				Microsoft SQL Server T/sql
 * Parameters:
 *						1: table; e.g. lookup_sahsu_grd_level1
 * 						2: Lookup column - shapefile table name, e.g. sahsu_grd_level1
 *						3: Schema; e.g. rif_data. or ""
 *
 * Description:			Create lookup table
 * Note:				%% becomes % after substitution
 */
CREATE TABLE lookup_cb_2014_us_nation_5m (
	cb_2014_us_nation_5m			NVARCHAR(100)  NOT NULL,
	areaname	NVARCHAR(1000),
	gid			INTEGER		  NOT NULL,
	geographic_centroid		VARCHAR(1000),
	PRIMARY KEY (cb_2014_us_nation_5m)
);


-- SQL statement 194: Comment table lookup_cb_2014_us_nation_5m >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_nation_5m';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table for The County at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table for The County at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m';


-- SQL statement 195: Comment lookup_cb_2014_us_nation_5m columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_nation_5m';
SELECT @columnName  = 'cb_2014_us_nation_5m';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'cb_2014_us_nation_5m'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'cb_2014_us_nation_5m';


-- SQL statement 196: Comment lookup_cb_2014_us_nation_5m columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_nation_5m';
SELECT @columnName  = 'gid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'GID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'gid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'GID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'gid';


-- SQL statement 197: Comment lookup_cb_2014_us_nation_5m columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_nation_5m';
SELECT @columnName  = 'areaname';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area Name field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'areaname'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area Name field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'areaname';


-- SQL statement 198: Comment lookup_cb_2014_us_nation_5m columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_nation_5m'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_nation_5m';
SELECT @columnName  = 'geographic_centroid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'geographic_centroid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_nation_5m',
		@level2type = N'Column', @level2name = 'geographic_centroid';


-- SQL statement 199: Drop table lookup_cb_2014_us_state_500k >>>
IF OBJECT_ID('lookup_cb_2014_us_state_500k', 'U') IS NOT NULL DROP TABLE lookup_cb_2014_us_state_500k;


-- SQL statement 200: Create table lookup_cb_2014_us_state_500k >>>
/*
 * SQL statement name: 	create_lookup_table.sql
 * Type:				Microsoft SQL Server T/sql
 * Parameters:
 *						1: table; e.g. lookup_sahsu_grd_level1
 * 						2: Lookup column - shapefile table name, e.g. sahsu_grd_level1
 *						3: Schema; e.g. rif_data. or ""
 *
 * Description:			Create lookup table
 * Note:				%% becomes % after substitution
 */
CREATE TABLE lookup_cb_2014_us_state_500k (
	cb_2014_us_state_500k			NVARCHAR(100)  NOT NULL,
	areaname	NVARCHAR(1000),
	gid			INTEGER		  NOT NULL,
	geographic_centroid		VARCHAR(1000),
	PRIMARY KEY (cb_2014_us_state_500k)
);


-- SQL statement 201: Comment table lookup_cb_2014_us_state_500k >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_state_500k';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table for The nation at a scale of 1:5,000,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table for The nation at a scale of 1:5,000,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k';


-- SQL statement 202: Comment lookup_cb_2014_us_state_500k columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_state_500k';
SELECT @columnName  = 'cb_2014_us_state_500k';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'cb_2014_us_state_500k'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'cb_2014_us_state_500k';


-- SQL statement 203: Comment lookup_cb_2014_us_state_500k columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_state_500k';
SELECT @columnName  = 'gid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'GID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'gid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'GID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'gid';


-- SQL statement 204: Comment lookup_cb_2014_us_state_500k columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_state_500k';
SELECT @columnName  = 'areaname';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area Name field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'areaname'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area Name field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'areaname';


-- SQL statement 205: Comment lookup_cb_2014_us_state_500k columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_state_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_state_500k';
SELECT @columnName  = 'geographic_centroid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'geographic_centroid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_state_500k',
		@level2type = N'Column', @level2name = 'geographic_centroid';


-- SQL statement 206: Drop table lookup_cb_2014_us_county_500k >>>
IF OBJECT_ID('lookup_cb_2014_us_county_500k', 'U') IS NOT NULL DROP TABLE lookup_cb_2014_us_county_500k;


-- SQL statement 207: Create table lookup_cb_2014_us_county_500k >>>
/*
 * SQL statement name: 	create_lookup_table.sql
 * Type:				Microsoft SQL Server T/sql
 * Parameters:
 *						1: table; e.g. lookup_sahsu_grd_level1
 * 						2: Lookup column - shapefile table name, e.g. sahsu_grd_level1
 *						3: Schema; e.g. rif_data. or ""
 *
 * Description:			Create lookup table
 * Note:				%% becomes % after substitution
 */
CREATE TABLE lookup_cb_2014_us_county_500k (
	cb_2014_us_county_500k			NVARCHAR(100)  NOT NULL,
	areaname	NVARCHAR(1000),
	gid			INTEGER		  NOT NULL,
	geographic_centroid		VARCHAR(1000),
	PRIMARY KEY (cb_2014_us_county_500k)
);


-- SQL statement 208: Comment table lookup_cb_2014_us_county_500k >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_county_500k';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table for The State at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Lookup table for The State at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k';


-- SQL statement 209: Comment lookup_cb_2014_us_county_500k columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_county_500k';
SELECT @columnName  = 'cb_2014_us_county_500k';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'cb_2014_us_county_500k'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'cb_2014_us_county_500k';


-- SQL statement 210: Comment lookup_cb_2014_us_county_500k columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_county_500k';
SELECT @columnName  = 'gid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'GID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'gid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'GID field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'gid';


-- SQL statement 211: Comment lookup_cb_2014_us_county_500k columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_county_500k';
SELECT @columnName  = 'areaname';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area Name field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'areaname'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area Name field',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'areaname';


-- SQL statement 212: Comment lookup_cb_2014_us_county_500k columns >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.lookup_cb_2014_us_county_500k'
ELSE
	SELECT @tableName = '@CurrentUser.lookup_cb_2014_us_county_500k';
SELECT @columnName  = 'geographic_centroid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'geographic_centroid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geographic centroid',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'lookup_cb_2014_us_county_500k',
		@level2type = N'Column', @level2name = 'geographic_centroid';


--
-- Insert Geolevels lookup tables
--

-- SQL statement 214: Insert table lookup_cb_2014_us_nation_5m >>>
/*
 * SQL statement name: 	insert_lookup_table.sql
 * Type:				Microsoft SQL Server T/sql
 * Parameters:
 *						1: lookup table; e.g. lookup_sahsu_grd_level1
 *						2: shapefile table; e.g. sahsu_grd_level4
 *
 * Description:			Insert data into lookup table
 *						Centroid JSON: {"type":"Point","coordinates":[-6.36447811663261,55.1846108882703]}
 * Note:				%% becomes % after substitution
 */
INSERT INTO lookup_cb_2014_us_nation_5m(cb_2014_us_nation_5m, areaname, gid, geographic_centroid)
SELECT areaid, areaname, ROW_NUMBER() OVER(ORDER BY areaid) AS gid,
	   '{"type":"Point","coordinates":[' + CAST(geographic_centroid.Long AS VARCHAR) +  ',' +
			CAST(geographic_centroid.Lat AS VARCHAR) + ']}' AS geographic_centroid
  FROM cb_2014_us_nation_5m
 ORDER BY 1;


(1 rows affected)

-- SQL statement 215: Insert table lookup_cb_2014_us_state_500k >>>
/*
 * SQL statement name: 	insert_lookup_table.sql
 * Type:				Microsoft SQL Server T/sql
 * Parameters:
 *						1: lookup table; e.g. lookup_sahsu_grd_level1
 *						2: shapefile table; e.g. sahsu_grd_level4
 *
 * Description:			Insert data into lookup table
 *						Centroid JSON: {"type":"Point","coordinates":[-6.36447811663261,55.1846108882703]}
 * Note:				%% becomes % after substitution
 */
INSERT INTO lookup_cb_2014_us_state_500k(cb_2014_us_state_500k, areaname, gid, geographic_centroid)
SELECT areaid, areaname, ROW_NUMBER() OVER(ORDER BY areaid) AS gid,
	   '{"type":"Point","coordinates":[' + CAST(geographic_centroid.Long AS VARCHAR) +  ',' +
			CAST(geographic_centroid.Lat AS VARCHAR) + ']}' AS geographic_centroid
  FROM cb_2014_us_state_500k
 ORDER BY 1;


(56 rows affected)

-- SQL statement 216: Insert table lookup_cb_2014_us_county_500k >>>
/*
 * SQL statement name: 	insert_lookup_table.sql
 * Type:				Microsoft SQL Server T/sql
 * Parameters:
 *						1: lookup table; e.g. lookup_sahsu_grd_level1
 *						2: shapefile table; e.g. sahsu_grd_level4
 *
 * Description:			Insert data into lookup table
 *						Centroid JSON: {"type":"Point","coordinates":[-6.36447811663261,55.1846108882703]}
 * Note:				%% becomes % after substitution
 */
INSERT INTO lookup_cb_2014_us_county_500k(cb_2014_us_county_500k, areaname, gid, geographic_centroid)
SELECT areaid, areaname, ROW_NUMBER() OVER(ORDER BY areaid) AS gid,
	   '{"type":"Point","coordinates":[' + CAST(geographic_centroid.Long AS VARCHAR) +  ',' +
			CAST(geographic_centroid.Lat AS VARCHAR) + ']}' AS geographic_centroid
  FROM cb_2014_us_county_500k
 ORDER BY 1;


(3233 rows affected)

--
-- Hierarchy table
--

-- SQL statement 218: Drop table hierarchy_usa_2014 >>>
IF OBJECT_ID('hierarchy_usa_2014', 'U') IS NOT NULL DROP TABLE hierarchy_usa_2014;


-- SQL statement 219: Create table hierarchy_usa_2014 >>>
CREATE TABLE hierarchy_usa_2014 (
	cb_2014_us_county_500k	VARCHAR(100)  NOT NULL,
	cb_2014_us_nation_5m	VARCHAR(100)  NOT NULL,
	cb_2014_us_state_500k	VARCHAR(100)  NOT NULL);


-- SQL statement 220: Add primary key hierarchy_usa_2014 >>>
ALTER TABLE hierarchy_usa_2014 ADD PRIMARY KEY (cb_2014_us_county_500k);


-- SQL statement 221: Add index key hierarchy_usa_2014_cb_2014_us_state_500k >>>
CREATE INDEX hierarchy_usa_2014_cb_2014_us_state_500k ON hierarchy_usa_2014 (cb_2014_us_state_500k);


-- SQL statement 222: Comment table: hierarchy_usa_2014 >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.hierarchy_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.hierarchy_usa_2014';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy lookup table for US 2014 Census geography to county level',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'hierarchy_usa_2014'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy lookup table for US 2014 Census geography to county level',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'hierarchy_usa_2014';


-- SQL statement 223: Comment column: hierarchy_usa_2014.cb_2014_us_county_500k >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.hierarchy_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.hierarchy_usa_2014';
SELECT @columnName  = 'cb_2014_us_county_500k';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy lookup for The County at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'hierarchy_usa_2014',
		@level2type = N'Column', @level2name = 'cb_2014_us_county_500k'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy lookup for The County at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'hierarchy_usa_2014',
		@level2type = N'Column', @level2name = 'cb_2014_us_county_500k';


-- SQL statement 224: Comment column: hierarchy_usa_2014.cb_2014_us_nation_5m >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.hierarchy_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.hierarchy_usa_2014';
SELECT @columnName  = 'cb_2014_us_nation_5m';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy lookup for The nation at a scale of 1:5,000,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'hierarchy_usa_2014',
		@level2type = N'Column', @level2name = 'cb_2014_us_nation_5m'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy lookup for The nation at a scale of 1:5,000,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'hierarchy_usa_2014',
		@level2type = N'Column', @level2name = 'cb_2014_us_nation_5m';


-- SQL statement 225: Comment column: hierarchy_usa_2014.cb_2014_us_state_500k >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.hierarchy_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.hierarchy_usa_2014';
SELECT @columnName  = 'cb_2014_us_state_500k';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy lookup for The State at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'hierarchy_usa_2014',
		@level2type = N'Column', @level2name = 'cb_2014_us_state_500k'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Hierarchy lookup for The State at a scale of 1:500,000',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'hierarchy_usa_2014',
		@level2type = N'Column', @level2name = 'cb_2014_us_state_500k';


-- SQL statement 226: Create function check_hierarchy_usa_2014 >>>
IF OBJECT_ID(N'check_hierarchy_usa_2014', N'P') IS NOT NULL
    DROP PROCEDURE check_hierarchy_usa_2014;

SELECT name, type, type_desc FROM sys.objects WHERE name = 'check_hierarchy_usa_2014';

name                                                                                                                             type type_desc
-------------------------------------------------------------------------------------------------------------------------------- ---- ------------------------------------------------------------

(0 rows affected)

CREATE PROCEDURE check_hierarchy_usa_2014(
	@l_geography 		VARCHAR(30),
	@l_hierarchytable 	VARCHAR(200),
	@l_type 			VARCHAR(30),
	@error_count 		INTEGER OUTPUT)
AS
/*
 * SQL statement name: 	check_hierarchy_function.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: function name; e.g. check_hierarchy_cb_2014_us_500k
 *
 * Description:			Create hierarchy check function
 * Note:				% becomes % after substitution
 */

/*
Function: 		check_hierarchy_usa_2014()
Parameters:		Geography, hierarchy table, type: 'missing', 'spurious additional' or 'multiple hierarchy'
Returns:		Nothing
Description:	Diff geography hierarchy table using dynamic method 4
				Also tests the hierarchy, i.e. all a higher resolutuion is contained by one of the next higher and so on

WITH /- multiple hierarchy -/ a2 AS (
        SELECT COUNT(*) AS cb_2014_us_state_500k_total
          FROM (
                SELECT cb_2014_us_state_500k, COUNT(DISTINCT(cb_2014_us_nation_5m)) AS total
                  FROM hierarchy_cb_2014_us_500k
                 GROUP BY cb_2014_us_state_500k
                HAVING COUNT(DISTINCT(cb_2014_us_nation_5m)) > 1) as2
), a3 AS (
        SELECT COUNT(*) AS cb_2014_us_county_500k_total
          FROM (
                SELECT cb_2014_us_county_500k, COUNT(DISTINCT(cb_2014_us_state_500k)) AS total
                  FROM hierarchy_cb_2014_us_500k
                 GROUP BY cb_2014_us_county_500k
                HAVING COUNT(DISTINCT(cb_2014_us_state_500k)) > 1) as3
)
SELECT CAST('cb_2014_us_state_500k' AS VARCHAR) AS col,
			a2.cb_2014_us_state_500k_total AS val
  FROM a2
UNION
SELECT CAST('cb_2014_us_county_500k' AS VARCHAR) AS col,
			a3.cb_2014_us_county_500k_total AS val
  FROM a3;

*/
BEGIN
	DECLARE c2 CURSOR FOR
		SELECT geolevel_id, geolevel_name, lookup_table
		  FROM geolevels_usa_2014
		 WHERE geography = @l_geography
		 ORDER BY geolevel_id;
--
	DECLARE @sql_stmt 				AS NVARCHAR(max)='XXX';
	DECLARE @i 						AS INTEGER=0;
--
	DECLARE @crlf					AS VARCHAR(2)=CHAR(10)+CHAR(13);
	DECLARE @tab					AS VARCHAR(1)=CHAR(9);
--
	DECLARE @geolevel_id 			AS INTEGER;
	DECLARE @geolevel_name		 	AS VARCHAR(200);
	DECLARE @lookup_table 			AS VARCHAR(200);
	DECLARE @previous_geolevel_name AS VARCHAR(200);
--
	SET @error_count=0;
	SET @sql_stmt='WITH /* ' + @l_type + ' */ ';
--
	OPEN c2;
	FETCH NEXT FROM c2 INTO @geolevel_id, @geolevel_name, @lookup_table;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @i+=1;
--
		IF @l_type = 'multiple hierarchy'
			BEGIN
				IF @i = 1
					noop:
				ELSE IF @i > 2
					SET @sql_stmt+=', ' + 'a' + CAST(@geolevel_id AS VARCHAR) + ' AS (' + @crlf +
							@tab + 'SELECT COUNT(*) AS ' + LOWER(@geolevel_name) + '_total' + @crlf +
							@tab + '  FROM (' + @crlf;
				ELSE
					SET @sql_stmt+='a' + CAST(@geolevel_id AS VARCHAR) + ' AS (' + @crlf +
							@tab + 'SELECT COUNT(*) AS ' + LOWER(@geolevel_name) + '_total' + @crlf +
							@tab + '  FROM (' + @crlf;
			END;
		ELSE
			BEGIN
				IF @i != 1
					SET @sql_stmt+=', ' + 'a' + CAST(@geolevel_id AS VARCHAR) + ' AS (' + @crlf;
				ELSE
					SET @sql_stmt+='a' + CAST(@geolevel_id AS VARCHAR) + ' AS (' + @crlf;
				SET @sql_stmt+=@tab + 'SELECT COUNT(*) AS ' + LOWER(@geolevel_name) + '_total' + @crlf +
					@tab + '  FROM (' + @crlf;
			END;
--
		IF @l_type = 'missing'
			SET @sql_stmt+=@tab + @tab + 'SELECT ' + LOWER(@geolevel_name) +
				' FROM ' + LOWER(@l_hierarchytable) + @crlf +
				@tab + @tab + 'EXCEPT' + @crlf +
				@tab + @tab + 'SELECT ' + LOWER(@geolevel_name) + ' FROM ' + LOWER(@lookup_table) +
				') as' + CAST(@geolevel_id AS VARCHAR) + ')' + @crlf;
		ELSE IF @l_type = 'spurious additional'
			SET @sql_stmt+=@tab + @tab + 'SELECT ' + LOWER(@geolevel_name) +
				' FROM ' + LOWER(@lookup_table) + @crlf +
				@tab + @tab + 'EXCEPT' + @crlf +
				@tab + @tab + 'SELECT ' + LOWER(@geolevel_name) + ' FROM ' + LOWER(@l_hierarchytable) +
				') as' + CAST(@geolevel_id AS VARCHAR) + ')' + @crlf;
		ELSE IF @l_type = 'multiple hierarchy'
			BEGIN
				IF @previous_geolevel_name IS NOT NULL
					SET @sql_stmt+=@tab + @tab + 'SELECT ' + LOWER(@geolevel_name) +
						', COUNT(DISTINCT(' + @previous_geolevel_name + ')) AS total' + @crlf +
						@tab + @tab + '  FROM ' + LOWER(@l_hierarchytable) + @crlf +
						@tab + @tab + ' GROUP BY ' + LOWER(@geolevel_name) + @crlf +
						@tab + @tab + 'HAVING COUNT(DISTINCT(' + @previous_geolevel_name + ')) > 1' +
						') as' + CAST(@geolevel_id AS VARCHAR) + ')' + @crlf;
			END;
		ELSE
			RAISERROR('Invalid check type: %s, valid types are: ''missing'', ''spurious additional'', or ''multiple hierarchy''',
				1, 16, @l_type 	/* Check type */);
		SET @previous_geolevel_name=LOWER(@geolevel_name);
--
		FETCH NEXT FROM c2 INTO @geolevel_id, @geolevel_name, @lookup_table;
	END;
	CLOSE c2;
--
	SET @i=0;
	OPEN c2;
	FETCH NEXT FROM c2 INTO @geolevel_id, @geolevel_name, @lookup_table;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @i+=1;
		IF @l_type = 'multiple hierarchy'
			BEGIN
			IF @i = 1
				noop2:
			ELSE IF @i > 2
				SET @sql_stmt+=@crlf + 'UNION' + @crlf + 'SELECT CAST(''' + LOWER(@geolevel_name) +
					''' AS VARCHAR) AS col, ' + @crlf +
					@tab + 'a' + CAST(@geolevel_id AS VARCHAR) + '.' +
					LOWER(@geolevel_name) + '_total AS val' + @crlf +
					'  FROM a' + CAST(@geolevel_id AS VARCHAR);
			ELSE
				SET @sql_stmt+='SELECT CAST(''' + LOWER(@geolevel_name) + ''' AS VARCHAR) AS col,' + @crlf +
					@tab + 'a' + CAST(@geolevel_id AS VARCHAR) + '.' + LOWER(@geolevel_name) +
					'_total AS val' + @crlf +
					'  FROM a' + CAST(@geolevel_id AS VARCHAR);
			END;
		ELSE
			BEGIN
			IF @i != 1
				SET @sql_stmt+=@crlf + 'UNION' + @crlf + 'SELECT CAST(''' + LOWER(@geolevel_name) +
					''' AS VARCHAR) AS col, ' + @crlf +
					@tab + 'a' + CAST(@geolevel_id AS VARCHAR) + '.' +
					LOWER(@geolevel_name) + '_total AS val' + @crlf +
					'  FROM a' + CAST(@geolevel_id AS VARCHAR);
			ELSE
				SET @sql_stmt+='SELECT CAST(''' + LOWER(@geolevel_name) + ''' AS VARCHAR) AS col,' + @crlf +
					@tab + 'a' + CAST(@geolevel_id AS VARCHAR) + '.' + LOWER(@geolevel_name) +
					'_total AS val' + @crlf +
					'  FROM a' + CAST(@geolevel_id AS VARCHAR);
			END;
--
		FETCH NEXT FROM c2 INTO @geolevel_id, @geolevel_name, @lookup_table;
	END;
	CLOSE c2;
--
	DEALLOCATE c2;
--
	PRINT 'SQL> ' + @sql_stmt;
    DECLARE @results AS TABLE (
		col VARCHAR(200), val NUMERIC)
	INSERT into @results EXECUTE sp_executesql @sql_stmt;
--
-- Process results table
--
	DECLARE @col AS VARCHAR(200);
	DECLARE @val AS NUMERIC;
	DECLARE c1 CURSOR FOR
		SELECT col, val
		  FROM @results;
	OPEN c1;
	FETCH NEXT FROM c1 INTO @col, @val;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT 'Geography: ' + @l_geography + ' geolevel: ' + @col + ' has ' + CAST(@val AS VARCHAR) +
			' ' + @l_type + ' codes';
		IF @val != 0
			SET @error_count+=1;
--
		FETCH NEXT FROM c1 INTO @col, @val;
	END;
	CLOSE c1;
--
	DEALLOCATE c1;
END;;


-- SQL statement 227: Comment function check_hierarchy_usa_2014 >>>
DECLARE @CurrentUser sysname  /*
 * SQL statement name: 	check_hierarchy_function_comment.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: function name; e.g. check_hierarchy_cb_2014_us_500k
 *
 * Description:			Create hierarchy check function comment
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty 'MS_Description',
   'Procedure: 		check_hierarchy_check_hierarchy_usa_2014()
Parameters:		Geography, hierarchy table, type: "missing", "spurious additional" or "multiple hierarchy",
				Error count (OUT)
Returns:		Nothing
Description:	Diff geography hierarchy table using dynamic method 4
				Also tests the hierarchy, i.e. all a higher resolutuion is contained by one of the next higher and so on

Example of dynamic SQL. Note the use of an array return type to achieve method 4

WITH /* missing */ a1 AS (
        SELECT COUNT(*) AS cb_2014_us_nation_5m_total
          FROM (
                SELECT cb_2014_us_nation_5m FROM hierarchy_cb_2014_us_500k
                EXCEPT
                SELECT cb_2014_us_nation_5m FROM lookup_cb_2014_us_nation_5m) as1)
, a2 AS (
        SELECT COUNT(*) AS cb_2014_us_state_500k_total
          FROM (
                SELECT cb_2014_us_state_500k FROM hierarchy_cb_2014_us_500k
                EXCEPT
                SELECT cb_2014_us_state_500k FROM lookup_cb_2014_us_state_500k) as2)
, a3 AS (
        SELECT COUNT(*) AS cb_2014_us_county_500k_total
          FROM (
                SELECT cb_2014_us_county_500k FROM hierarchy_cb_2014_us_500k
                EXCEPT
                SELECT cb_2014_us_county_500k FROM lookup_cb_2014_us_county_500k) as3)
SELECT ARRAY[a1.cb_2014_us_nation_5m_total, a2.cb_2014_us_state_500k_total, a3.cb_2014_us_county_500k_total] AS res_array
FROM a1, a2, a3;

Or:

WITH /* multiple hierarchy */ a2 AS (
        SELECT COUNT(*) AS cb_2014_us_state_500k_total
          FROM (
                SELECT cb_2014_us_state_500k, COUNT(DISTINCT(cb_2014_us_nation_5m)) AS total
                  FROM hierarchy_cb_2014_us_500k
                 GROUP BY cb_2014_us_state_500k
                HAVING COUNT(DISTINCT(cb_2014_us_nation_5m)) > 1) as2)
, a3 AS (
        SELECT COUNT(*) AS cb_2014_us_county_500k_total
          FROM (
                SELECT cb_2014_us_county_500k, COUNT(DISTINCT(cb_2014_us_state_500k)) AS total
                  FROM hierarchy_cb_2014_us_500k
                 GROUP BY cb_2014_us_county_500k
                HAVING COUNT(DISTINCT(cb_2014_us_state_500k)) > 1) as3)
SELECT ARRAY[a2.cb_2014_us_state_500k_total, a3.cb_2014_us_county_500k_total] AS res_array
FROM a2, a3;
',
   'user', @CurrentUser,
   'procedure', 'check_hierarchy_usa_2014';


-- SQL statement 228: Insert into hierarchy_usa_2014 >>>
DECLARE @l_geography AS VARCHAR(200)='USA_2014';
/*
 * SQL statement name: 	insert_hierarchy.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geography; e.g. cb_2014_us_500k
 *						2: Max zoomlevel
 *
 * Description:			Create insert statement into hierarchy table
 * Note:				%% becomes % after substitution
 *
 * Output for SAHSULAND:

Populating SAHSULAND geography hierarchy table: HIERARCHY_SAHSULAND; spid: 52
SQL> SELECT /- Subqueries x12 ... x34: intersection aggregate geometries starting from the lowest resolution.
               Created using N-1 geoevels cross joins rather than 1 to minimise cross join size and hence improve performance.
               Calculate the area of the higher resolution geolevel and the area of the intersected area -/
       a1.areaid AS SAHSU_GRD_LEVEL1,
       a2.areaid AS SAHSU_GRD_LEVEL2,
       a2.geom_orig.STArea() AS a2_area,
       a1.geom_orig.STIntersection(a2.geom_orig).STArea() AS a12_area
  INTO ##x12_52
  FROM SAHSU_GRD_LEVEL1 a1 CROSS JOIN SAHSU_GRD_LEVEL2 a2
 WHERE a1.geom_orig.STIntersects(a2.geom_orig) = 1

(17 rows affected)
SQL> SELECT /- Subqueries x23 ... x34: intersection aggregate geometries starting from the lowest resolution.
               Created using N-1 geoevels cross joins rather than 1 to minimise cross join size and hence improve performance.
               Calculate the area of the higher resolution geolevel and the area of the intersected area -/
       a2.areaid AS SAHSU_GRD_LEVEL2,
       a3.areaid AS SAHSU_GRD_LEVEL3,
       a3.geom_orig.STArea() AS a3_area,
       a2.geom_orig.STIntersection(a3.geom_orig).STArea() AS a23_area
  INTO ##x23_52
  FROM SAHSU_GRD_LEVEL2 a2 CROSS JOIN SAHSU_GRD_LEVEL3 a3
 WHERE a2.geom_orig.STIntersects(a3.geom_orig) = 1

(331 rows affected)
SQL> SELECT /- Subqueries x34 ... x34: intersection aggregate geometries starting from the lowest resolution.
               Created using N-1 geoevels cross joins rather than 1 to minimise cross join size and hence improve performance.
               Calculate the area of the higher resolution geolevel and the area of the intersected area -/
       a3.areaid AS SAHSU_GRD_LEVEL3,
       a4.areaid AS SAHSU_GRD_LEVEL4,
       a4.geom_orig.STArea() AS a4_area,
       a3.geom_orig.STIntersection(a4.geom_orig).STArea() AS a34_area
  INTO ##x34_52
  FROM SAHSU_GRD_LEVEL3 a3 CROSS JOIN SAHSU_GRD_LEVEL4 a4
 WHERE a3.geom_orig.STIntersects(a4.geom_orig) = 1

(50954 rows affected)
SQL>
SELECT /- Join x45 ... x34intersections, pass through the computed areas, compute intersected area/higher resolution geolevel area,
             compute maximum intersected area/higher resolution geolevel area using an analytic partition of all
             duplicate higher resolution geolevels -/
               x12.SAHSU_GRD_LEVEL1,
               x12.SAHSU_GRD_LEVEL2,
               x23.SAHSU_GRD_LEVEL3,
               x34.SAHSU_GRD_LEVEL4,
               CASE WHEN x12.a2_area > 0 THEN x12.a12_area/x12.a2_area ELSE NULL END test12,
               MAX(x12.a12_area/x12.a2_area) OVER (PARTITION BY x12.SAHSU_GRD_LEVEL2) AS max12,
               CASE WHEN x23.a3_area > 0 THEN x23.a23_area/x23.a3_area ELSE NULL END test23,
               MAX(x23.a23_area/x23.a3_area) OVER (PARTITION BY x23.SAHSU_GRD_LEVEL3) AS max23,
               CASE WHEN x34.a4_area > 0 THEN x34.a34_area/x34.a4_area ELSE NULL END test34,
               MAX(x34.a34_area/x34.a4_area) OVER (PARTITION BY x34.SAHSU_GRD_LEVEL4) AS max34
  INTO ##y_52
  FROM ##x12_52 x12, ##x23_52 x23, ##x34_52 x34
 WHERE x12.SAHSU_GRD_LEVEL2 = x23.SAHSU_GRD_LEVEL2
   AND x23.SAHSU_GRD_LEVEL3 = x34.SAHSU_GRD_LEVEL3

(84488 rows affected)
SQL> DROP TABLE ##x12_52
SQL> DROP TABLE ##x23_52
SQL> DROP TABLE ##x34_52
SQL> INSERT INTO hierarchy_sahsuland (sahsu_grd_level1, sahsu_grd_level2, sahsu_grd_level3, sahsu_grd_level4)
SELECT /- Select y intersection, eliminating duplicates using selecting the lower geolevel resolution
         with the largest intersection by area for each (higher resolution) geolevel -/
       sahsu_grd_level1, sahsu_grd_level2, sahsu_grd_level3, sahsu_grd_level4
  FROM ##y_52
 WHERE max12 = test12
   AND max12 > 0.5 /- >50% overlap -/
   AND max23 = test23
   AND max23 > 0.5 /- >50% overlap -/
   AND max34 = test34
   AND max34 > 0.5 /- >50% overlap -/
 ORDER BY 1, 2, 3, 4

(1230 rows affected)
SQL> DROP TABLE ##y_52
name
--------------------------------------------------------------------------------------------------------------------------------

(0 rows affected)
SQL> ALTER INDEX hierarchy_sahsuland_sahsu_grd_level2 ON hierarchy_sahsuland REORGANIZE
SQL> ALTER INDEX hierarchy_sahsuland_sahsu_grd_level3 ON hierarchy_sahsuland REORGANIZE
SQL> ALTER INDEX PK__hierarch__61FEBAD4794A035D ON hierarchy_sahsuland REORGANIZE
SQL> UPDATE STATISTICS hierarchy_sahsuland

 */
--

--
DECLARE c1_hier CURSOR FOR
		SELECT geolevel_id, geolevel_name, shapefile_table, shapefile_area_id_column, shapefile_desc_column
		  FROM geolevels_USA_2014
		 WHERE geography = @l_geography
		 ORDER BY geography, geolevel_id;
DECLARE c2_hier CURSOR FOR
		SELECT i.name AS index_name,
		       object_name(object_id) AS table_name
  		  FROM sys.indexes i
		 WHERE i.object_id = (
					 SELECT object_id(LOWER(hierarchytable))
				       FROM geography_USA_2014
				      WHERE geography = @l_geography)
		 ORDER BY 1;
DECLARE c4_hier CURSOR FOR
	SELECT geography, hierarchytable
		  FROM geography_USA_2014
		 WHERE geography = @l_geography;
DECLARE @c3 CURSOR;
DECLARE @geography		AS	VARCHAR(200);
DECLARE @hierarchytable AS 	VARCHAR(200);
--
DECLARE @columns		AS	VARCHAR(200);
DECLARE @sql_stmt	 	AS	NVARCHAR(max);
DECLARE @num_geolevels	AS	INTEGER=0;
--
DECLARE @geolevel_id 				AS INTEGER;
DECLARE @geolevel_name 				AS VARCHAR(200);
DECLARE @shapefile_table		 	AS VARCHAR(200);
DECLARE @shapefile_area_id_column 	AS VARCHAR(200);
DECLARE @shapefile_desc_column 		AS VARCHAR(200);
DECLARE @n_geolevel_name 			AS VARCHAR(200);
DECLARE @n_shapefile_table		 	AS VARCHAR(200);
DECLARE @n_shapefile_area_id_column AS VARCHAR(200);
DECLARE @n_shapefile_desc_column 	AS VARCHAR(200);
--
DECLARE @tablename	 	AS VARCHAR(200);
DECLARE @indexname	 	AS VARCHAR(200);

DECLARE @i 				AS INTEGER=0;
--
DECLARE @crlf			AS VARCHAR(2)=CHAR(10)+CHAR(13);
DECLARE @tab			AS VARCHAR(1)=CHAR(9);
--
DECLARE @rowcount		AS INTEGER=0;

--
BEGIN
--
	OPEN c4_hier;
	FETCH c4_hier INTO @geography, @hierarchytable;
	CLOSE c4_hier;
	DEALLOCATE c4_hier;
--
	IF @geography IS NULL
		RAISERROR('geography: %s not found', 16, 1, @l_geography	/* Geography */);
--
	 PRINT 'Populating ' + @l_geography + ' geography hierarchy table: ' + @hierarchytable +
		'; spid: ' + CAST(@@spid AS VARCHAR);

	SET @num_geolevels=0;
	OPEN c1_hier;
	FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
								 @shapefile_area_id_column, @shapefile_desc_column;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @num_geolevels+=1;
		IF @num_geolevels = 1
			SET @columns=LOWER(@geolevel_name);
		ELSE
			SET @columns+=', ' + LOWER(@geolevel_name);
		FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
									 @shapefile_area_id_column, @shapefile_desc_column;
	END;
	CLOSE c1_hier;
--
	IF @num_geolevels = 0
		RAISERROR('No rows found in: geolevels_%s for geography %s', 16, 1, @l_geography, @l_geography);
--
-- CTE x<n><n+1> - CROSS JOINs with intersections
--
	OPEN c1_hier;
	FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
								 @shapefile_area_id_column, @shapefile_desc_column;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @i+=1;

		DECLARE c1a_hier CURSOR FOR
				SELECT geolevel_name, shapefile_table, shapefile_area_id_column, shapefile_desc_column
				  FROM geolevels_USA_2014
				 WHERE geography   = @l_geography
				   AND geolevel_id = @geolevel_id+1
				 ORDER BY geography, geolevel_id;
		OPEN c1a_hier;
		FETCH NEXT FROM c1a_hier INTO @n_geolevel_name, @n_shapefile_table,
									  @n_shapefile_area_id_column, @n_shapefile_desc_column;
		CLOSE c1a_hier;
		DEALLOCATE c1a_hier;

--		PRINT 'i: ' + CAST(@i AS VARCHAR) + '; num_geolevels: ' + CAST(@num_geolevels AS VARCHAR) +
--			'; geolevel_name: ' + @geolevel_name + '; n_geolevel_name: ' + @n_geolevel_name;
		IF @i = 1
/* E.g

SELECT a1.areaid AS cb_2014_us_nation_5m,
	   a2.areaid AS cb_2014_us_state_500k,
	   a2.geom_orig.STArea() AS a2_area,
	   a1.geom_orig.STIntersection(a2.geom_orig).STArea() AS a12_area
  INTO dbo.#x12
  FROM cb_2014_us_nation_5m a1   CROSS JOIN cb_2014_us_state_500k a2
 WHERE a1.geom_orig.STIntersects(a2.geom_orig) = 1;

Postgres Original:

x23 AS (
	SELECT a2.areaid AS level2,
       	   a3.areaid AS level3,
  	       ST_Area(a3.geom) AS a3_area,
	       ST_Area(ST_Intersection(a2.geom, a3.geom)) AS a23_area
          FROM a2 CROSS JOIN a3
	 WHERE ST_Intersects(a2.geom, a3.geom)

SQL Server:

SELECT a1.areaid AS SAHSU_GRD_LEVEL1,
       a2.areaid AS SAHSU_GRD_LEVEL2,
       a2.geom_orig.STArea() AS a2_area,
       a1.geom_orig.STIntersection(a2.geom_orig).STArea() AS a12_area
  INTO x12_52
  FROM SAHSU_GRD_LEVEL1 a1 CROSS JOIN SAHSU_GRD_LEVEL2 a2
 WHERE a1.geom_orig.STIntersects(a2.geom_orig) = 1
   AND a1.geom_orig.STIntersection(a2.geom_orig).STArea() > 0;

 */
			BEGIN
				SET @sql_stmt=
					'SELECT /* Subqueries x' +
						CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + ' ... x' +
						CAST(@num_geolevels-1 AS VARCHAR) + CAST(@num_geolevels AS VARCHAR) +
						': intersection aggregate geometries starting from the lowest resolution.' + @crlf +
						@tab + '       Created using N-1 geoevels cross joins rather than 1 to minimise cross join size and hence improve performance.' + @crlf +
						@tab + '       Calculate the area of the higher resolution geolevel and the area of the intersected area */' + @crlf +
					'       a' + CAST(@i AS VARCHAR) + '.areaid AS ' + @geolevel_name + ',' + @crlf +
					'       a' + CAST(@i+1 AS VARCHAR) + '.areaid AS ' + @n_geolevel_name + ',' + @crlf +
					'       a' + CAST(@i+1 AS VARCHAR) + '.geom_orig.STArea() AS a' + CAST(@i+1 AS VARCHAR) + '_area,' + @crlf +
					'       a' + CAST(@i AS VARCHAR) + '.geom_orig.STIntersection(a' + CAST(@i+1 AS VARCHAR) + '.geom_orig).STArea() AS a' +
						CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '_area' + @crlf +
				    '  INTO ##x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '_' + CAST(@@spid AS VARCHAR) + @crlf +
					'  FROM ' + @shapefile_table + ' a' + CAST(@i AS VARCHAR) +
					' CROSS JOIN ' + @n_shapefile_table + ' a' + CAST(@i+1 AS VARCHAR) + '' + @crlf +
					' WHERE a' + CAST(@i AS VARCHAR) + '.geom_orig.STIntersects(a' + CAST(@i+1 AS VARCHAR) + '.geom_orig) = 1' + @crlf +
					'   AND a' + CAST(@i AS VARCHAR) + '.geom_orig.STIntersection(a' + CAST(@i+1 AS VARCHAR) + '.geom_orig).STArea() > 0';
				PRINT 'SQL> ' + @sql_stmt;
				EXECUTE @rowcount = sp_executesql @sql_stmt;
			END;
		ELSE IF @i < (@num_geolevels-1)
/* E.g

SELECT a2.areaid AS cb_2014_us_state_500k,
	   a3.areaid AS cb_2014_us_county_500k,
	   a3.geom_orig.STArea() AS a3_area,
	   a2.geom_orig.STIntersection(a3.geom_orig).ST_Area() AS a23_area
  INTO dbo.#x23
  FROM cb_2014_us_state_500k a2  CROSS JOIN cb_2014_us_county_500k a3
 WHERE a2.geom_orig.STntersects(a3.geom_orig) = 1;

*/
			BEGIN
				SET @sql_stmt=
					'SELECT /* Subqueries x' +
						CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + ' ... x' +
						CAST(@num_geolevels-1 AS VARCHAR) + CAST(@num_geolevels AS VARCHAR) +
						': intersection aggregate geometries starting from the lowest resolution.' + @crlf +
						@tab + '       Created using N-1 geoevels cross joins rather than 1 to minimise cross join size and hence improve performance.' + @crlf +
						@tab + '       Calculate the area of the higher resolution geolevel and the area of the intersected area */' + @crlf +
					'       a' + CAST(@i AS VARCHAR) + '.areaid AS ' + @geolevel_name + ',' + @crlf +
					'       a' + CAST(@i+1 AS VARCHAR) + '.areaid AS ' + @n_geolevel_name + ',' + @crlf +
					'       a' + CAST(@i+1 AS VARCHAR) + '.geom_orig.STArea() AS a' + CAST(@i+1 AS VARCHAR) + '_area,' + @crlf +
					'       a' + CAST(@i AS VARCHAR) + '.geom_orig.STIntersection(a' + CAST(@i+1 AS VARCHAR) + '.geom_orig).STArea() AS a' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '_area' + @crlf +
				    '  INTO ##x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '_' + CAST(@@spid AS VARCHAR) + @crlf +
					'  FROM ' + @shapefile_table + ' a' + CAST(@i AS VARCHAR) +
					' CROSS JOIN ' + @n_shapefile_table + ' a' + CAST(@i+1 AS VARCHAR) + '' + @crlf +
					' WHERE a' + CAST(@i AS VARCHAR) + '.geom_orig.STIntersects(a' + CAST(@i+1 AS VARCHAR) +
						'.geom_orig) = 1';
				PRINT 'SQL> ' + @sql_stmt;
				EXECUTE @rowcount = sp_executesql @sql_stmt;
			END;
		ELSE IF @i < @num_geolevels
/* E.g.

SELECT a2.areaid AS cb_2014_us_state_500k,
	   a3.areaid AS cb_2014_us_county_500k,
	   a3.geom_orig.STArea() AS a3_area,
	   a2.geom_orig.STIntersection(a3.geom_orig).STArea() AS a23_area
  INTO dbo.#x23
  FROM cb_2014_us_state_500k a2 CROSS JOIN cb_2014_us_county_500k a3
 WHERE a2.geom_orig.STIntersects(a3.geom_orig) = 1;

Postgres Original:

 x34 AS (
	SELECT a3.level3,
	       a4.level4,
  	       ST_Area(a4.geom) AS a4_area,
	       ST_Area(ST_Intersection(a3.geom, a4.geom)) a34_area
          FROM a3 CROSS JOIN a4
	 WHERE ST_Intersects(a3.geom, a4.geom)
*/
			BEGIN
				SET @sql_stmt=
					'SELECT /* Subqueries x' +
						CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + ' ... x' +
						CAST(@num_geolevels-1 AS VARCHAR) + CAST(@num_geolevels AS VARCHAR) +
						': intersection aggregate geometries starting from the lowest resolution.' + @crlf +
						@tab + '       Created using N-1 geoevels cross joins rather than 1 to minimise cross join size and hence improve performance.' + @crlf +
						@tab + '       Calculate the area of the higher resolution geolevel and the area of the intersected area */' + @crlf +
					'       a' + CAST(@i AS VARCHAR) + '.areaid AS ' + @geolevel_name + ',' + @crlf +
					'       a' + CAST(@i+1 AS VARCHAR) + '.areaid AS ' + @n_geolevel_name + ',' + @crlf +
					'       a' + CAST(@i+1 AS VARCHAR) + '.geom_orig.STArea() AS a' + CAST(@i+1 AS VARCHAR) + '_area,' + @crlf +
					'       a' + CAST(@i AS VARCHAR) + '.geom_orig.STIntersection(a' + CAST(@i+1 AS VARCHAR) + '.geom_orig).STArea() AS a' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '_area' + @crlf +
				    '  INTO ##x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '_' + CAST(@@spid AS VARCHAR) + @crlf +
					'  FROM ' + @shapefile_table + ' a' + CAST(@i AS VARCHAR) + ' CROSS JOIN ' + @n_shapefile_table + ' a' + CAST(@i+1 AS VARCHAR) + '' + @crlf +
					' WHERE a' + CAST(@i AS VARCHAR) + '.geom_orig.STIntersects(a' + CAST(@i+1 AS VARCHAR) +
						'.geom_orig) = 1';
				PRINT 'SQL> ' + @sql_stmt;
				EXECUTE @rowcount = sp_executesql @sql_stmt;
			END;
		FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
									 @shapefile_area_id_column, @shapefile_desc_column;
	END;
	CLOSE c1_hier;
--
-- CTE: y - compute intersected area, order analytically
--

/*
	SELECT x12.level1, x12.level2, x23.level3, x34.level4,
	       CASE WHEN a2_area > 0 THEN a12_area/a2_area ELSE NULL END test12,
	       CASE WHEN a3_area > 0 THEN a23_area/a3_area ELSE NULL END test23,
	       CASE WHEN a4_area > 0 THEN a34_area/a4_area ELSE NULL END test34,
	       MAX(a12_area/a2_area) OVER (PARTITION BY x12.level2) AS max12,
	       MAX(a23_area/a3_area) OVER (PARTITION BY x23.level3) AS max23,
	       MAX(a34_area/a4_area) OVER (PARTITION BY x34.level4) AS max34
	  INTO #y
	  FROM x12, x23, x34
	 WHERE x12.level2 = x23.level2
   	   AND x23.level3 = x34.level3;
)
 */
	SET @sql_stmt=@crlf +
		'SELECT /* Join x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + ' ... x' + CAST(@num_geolevels-1 AS VARCHAR) + CAST(@num_geolevels AS VARCHAR) +
			'intersections, pass through the computed areas, compute intersected area/higher resolution geolevel area,' + @crlf +
		@tab + '     compute maximum intersected area/higher resolution geolevel area using an analytic partition of all' + @crlf +
		@tab + '     duplicate higher resolution geolevels */' + @crlf;
--
-- First line of SELECT statement
--
	SET @i=0;
	OPEN c1_hier;
	FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
								 @shapefile_area_id_column, @shapefile_desc_column;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @i+=1;

		DECLARE c1a_hier CURSOR FOR
				SELECT geolevel_name, shapefile_table, shapefile_area_id_column, shapefile_desc_column
				  FROM geolevels_USA_2014
				 WHERE geography   = @l_geography
				   AND geolevel_id = @geolevel_id+1
				 ORDER BY geography, geolevel_id;
		OPEN c1a_hier;
		FETCH NEXT FROM c1a_hier INTO @n_geolevel_name, @n_shapefile_table,
									  @n_shapefile_area_id_column, @n_shapefile_desc_column;
		CLOSE c1a_hier;
		DEALLOCATE c1a_hier;

--		PRINT 'i: ' + CAST(@i AS VARCHAR) + '; num_geolevels: ' + CAST(@num_geolevels AS VARCHAR) +
--			'; geolevel_name: ' + @geolevel_name + '; n_geolevel_name: ' + @n_geolevel_name;

		IF @i < @num_geolevels
		BEGIN
			IF @i = 1
				SET @sql_stmt+=
					@tab + '       x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '.' +
						@geolevel_name + ', ' + @crlf;
			SET @sql_stmt+=
				@tab + '       x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '.' +
					@n_geolevel_name + ', ' + @crlf;
		END;

		FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
									 @shapefile_area_id_column, @shapefile_desc_column;
	END;
	CLOSE c1_hier;
--
-- Add CASE, MAX lines
--
	SET @i=0;
	OPEN c1_hier;
	FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
								 @shapefile_area_id_column, @shapefile_desc_column;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @i+=1;

		DECLARE c1a_hier CURSOR FOR
				SELECT geolevel_name, shapefile_table, shapefile_area_id_column, shapefile_desc_column
				  FROM geolevels_USA_2014
				 WHERE geography   = @l_geography
				   AND geolevel_id = @geolevel_id+1
				 ORDER BY geography, geolevel_id;
		OPEN c1a_hier;
		FETCH NEXT FROM c1a_hier INTO @n_geolevel_name, @n_shapefile_table,
									  @n_shapefile_area_id_column, @n_shapefile_desc_column;
		CLOSE c1a_hier;
		DEALLOCATE c1a_hier;

--		PRINT 'i: ' + CAST(@i AS VARCHAR) + '; num_geolevels: ' + CAST(@num_geolevels AS VARCHAR) +
--			'; geolevel_name: ' + @geolevel_name + '; n_geolevel_name: ' + @n_geolevel_name;

		IF @i < @num_geolevels
		BEGIN
			SET @sql_stmt+=
	    		@tab + '       CASE WHEN x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '.a' +
						CAST(@i+1 AS VARCHAR) + '_area > 0 THEN x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) +
						'.a' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '_area/x' +
						CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '.a' + CAST(@i+1 AS VARCHAR) +
					'_area ELSE NULL END test' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + ',' + @crlf +
				@tab + '       MAX(x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '.a' +
					CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '_area/x' +
					CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '.a' + CAST(@i+1 AS VARCHAR) + '_area)' +
					' OVER (PARTITION BY x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) +
					'.' + @n_geolevel_name + ') AS max' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + ',' + @crlf;
		END;

		FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
									 @shapefile_area_id_column, @shapefile_desc_column;
	END;
	CLOSE c1_hier;
--
-- Trim last CRLF
--
	SET @sql_stmt=SUBSTRING(@sql_stmt, 1, LEN(@sql_stmt)-LEN(','+@crlf)) /* Chop off last ",\r\n" */ + @crlf;
--
-- Add INTO clause
--
	SET @sql_stmt+='  INTO ##y' + '_' + CAST(@@spid AS VARCHAR) + @crlf;
--
-- Add FROM clause
--
	SET @i=0;
	OPEN c1_hier;
	FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
								 @shapefile_area_id_column, @shapefile_desc_column;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @i+=1;

--		PRINT 'i: ' + CAST(@i AS VARCHAR) + '; num_geolevels: ' + CAST(@num_geolevels AS VARCHAR) +
--			'; geolevel_name: ' + @geolevel_name + '; n_geolevel_name: ' + @n_geolevel_name;

		IF @i < @num_geolevels
		BEGIN
			IF @i = 1
				SET @sql_stmt+='  FROM ##x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) +
					'_' + CAST(@@spid AS VARCHAR) +
					' x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR);
			ELSE
				SET @sql_stmt+=', ##x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) +
					'_' + CAST(@@spid AS VARCHAR) +
					' x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR);
		END;

		FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
									 @shapefile_area_id_column, @shapefile_desc_column;
	END;
	CLOSE c1_hier;
--
-- Add WHERE clause
--
	SET @i=0;
	OPEN c1_hier;
	FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
								 @shapefile_area_id_column, @shapefile_desc_column;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @i+=1;

		DECLARE c1a_hier CURSOR FOR
				SELECT geolevel_name, shapefile_table, shapefile_area_id_column, shapefile_desc_column
				  FROM geolevels_USA_2014
				 WHERE geography   = @l_geography
				   AND geolevel_id = @geolevel_id+1
				 ORDER BY geography, geolevel_id;
		OPEN c1a_hier;
		FETCH NEXT FROM c1a_hier INTO @n_geolevel_name, @n_shapefile_table,
									  @n_shapefile_area_id_column, @n_shapefile_desc_column;
		CLOSE c1a_hier;
		DEALLOCATE c1a_hier;

--		PRINT 'i: ' + CAST(@i AS VARCHAR) + '; num_geolevels: ' + CAST(@num_geolevels AS VARCHAR) +
--			'; geolevel_name: ' + @geolevel_name + '; n_geolevel_name: ' + @n_geolevel_name;

		IF @i < (@num_geolevels-1) /* FOR i IN 1 .. (num_geolevels-2) LOOP */
		BEGIN
			IF @i = 1
				SET @sql_stmt+=@crlf +
					' WHERE x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '.' + @n_geolevel_name +
						' = x' + CAST(@i+1 AS VARCHAR) + CAST(@i+2 AS VARCHAR) + '.' + @n_geolevel_name;
			ELSE
				SET @sql_stmt+=@crlf +
					'   AND x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + '.' + @n_geolevel_name +
						' = x' + CAST(@i+1 AS VARCHAR) + CAST(@i+2 AS VARCHAR) + '.' + @n_geolevel_name;
		END;
		FETCH NEXT FROM c1_hier INTO @geolevel_id, @geolevel_name, @shapefile_table,
									 @shapefile_area_id_column, @shapefile_desc_column;
	END;
	CLOSE c1_hier;
--
-- Run SQL to create Y
--
	PRINT 'SQL> ' + @sql_stmt;
	EXECUTE @rowcount = sp_executesql @sql_stmt;
--
-- Drop x_NN temporary tables
--
	SET @i=1;
	WHILE @i < @num_geolevels
	BEGIN
		SET @sql_stmt='DROP TABLE ##x' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) +
				 '_' + CAST(@@spid AS VARCHAR);
		PRINT 'SQL> ' + @sql_stmt;
		EXECUTE @rowcount = sp_executesql @sql_stmt;
		SET @i+=1;
	END;

--
-- Insert statement and columns
--
	SET @sql_stmt='INSERT INTO ' + LOWER(@hierarchytable) + ' (' + @columns + ')' + @crlf;

--
-- Final SELECT
--
/*
SELECT level1, level2, level3, level4,
  FROM y
 WHERE max12 = test12
   AND max23 = test23
   AND max34 = test34
 ORDER BY 1, 2, 3, 4;
 */
	SET @sql_stmt+='SELECT /* Select y intersection, eliminating duplicates using selecting the lower geolevel resolution' + @crlf +
         @tab + ' with the largest intersection by area for each (higher resolution) geolevel */' + @crlf + '       ' + @columns + @crlf +
		'  FROM ##y_' + CAST(@@spid AS VARCHAR) + @crlf;
--
-- WHERE clause
--
	SET @i=1;
	WHILE @i < @num_geolevels
	BEGIN
		IF @i = 1
			SET @sql_stmt+=' WHERE max' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) +
				' = test' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + @crlf;
		ELSE
			SET @sql_stmt+='   AND max' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) +
				' = test' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + @crlf;
--
-- Remove all joins that have <50% overlap
--
		SET @sql_stmt+='   AND max' + CAST(@i AS VARCHAR) + CAST(@i+1 AS VARCHAR) + ' > 0.5 /* >50% overlap */' + @crlf;

		SET @i+=1;
	END;
--
-- ORDER BY clause
--
	SET @sql_stmt+=' ORDER BY 1';
	SET @i=2;
	WHILE @i <= @num_geolevels /* FOR i IN 2 .. num_geolevels LOOP */
	BEGIN
		SET @sql_stmt+=', ' + CAST(@i AS VARCHAR);
		SET @i+=1;
	END;
--
	DEALLOCATE c1_hier;
--
	PRINT 'SQL> ' + @sql_stmt;
--
-- Execute SQL statement
--
	EXECUTE @i=sp_executesql @sql_stmt
	SET @rowcount = @@ROWCOUNT;
--
-- Drop Y temp table
--
	SET @sql_stmt='DROP TABLE ##y_' + CAST(@@spid AS VARCHAR);
	PRINT 'SQL> ' + @sql_stmt;
	EXECUTE sp_executesql @sql_stmt;
	SELECT name FROM tempdb.sys.objects;
--
-- Check rows were inserted
--
	IF @rowcount = 0
		RAISERROR('No rows found in %s geography hierarchy table: %s; sp_executesql rval: %d', 16, 1,
			@l_geography 			/* Geography */,
			@hierarchytable			/* Hierarchy table */,
			@i						/* Return value from sp_executesql() */);
--
-- Re-index
--
	OPEN c2_hier;
	FETCH NEXT FROM c2_hier INTO @indexname, @tablename;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @sql_stmt='ALTER INDEX ' + @indexname + ' ON ' + @tablename + ' REORGANIZE';
		PRINT 'SQL> ' + @sql_stmt;
		EXECUTE sp_executesql @sql_stmt;
		FETCH NEXT FROM c2_hier INTO @indexname, @tablename;
	END;
	CLOSE c2_hier;
	DEALLOCATE c2_hier;
--
-- Analyze
--
	SET @sql_stmt='UPDATE STATISTICS ' + LOWER(@hierarchytable);
	PRINT 'SQL> ' + @sql_stmt;
	EXECUTE sp_executesql @sql_stmt;
END;

Populating USA_2014 geography hierarchy table: HIERARCHY_USA_2014; spid: 51
SQL> SELECT /* Subqueries x12 ... x23: intersection aggregate geometries starting from the lowest resolution.

	       Created using N-1 geoevels cross joins rather than 1 to minimise cross join size and hence improve performance.

	       Calculate the area of the higher resolution geolevel and the area of the intersected area */

       a1.areaid AS CB_2014_US_NATION_5M,

       a2.areaid AS CB_2014_US_STATE_500K,

       a2.geom_orig.STArea() AS a2_area,

       a1.geom_orig.STIntersection(a2.geom_orig).STArea() AS a12_area

  INTO ##x12_51

  FROM CB_2014_US_NATION_5M a1 CROSS JOIN CB_2014_US_STATE_500K a2

 WHERE a1.geom_orig.STIntersects(a2.geom_orig) = 1

   AND a1.geom_orig.STIntersection(a2.geom_orig).STArea() > 0

(56 rows affected)
SQL> SELECT /* Subqueries x23 ... x23: intersection aggregate geometries starting from the lowest resolution.

	       Created using N-1 geoevels cross joins rather than 1 to minimise cross join size and hence improve performance.

	       Calculate the area of the higher resolution geolevel and the area of the intersected area */

       a2.areaid AS CB_2014_US_STATE_500K,

       a3.areaid AS CB_2014_US_COUNTY_500K,

       a3.geom_orig.STArea() AS a3_area,

       a2.geom_orig.STIntersection(a3.geom_orig).STArea() AS a23_area

  INTO ##x23_51

  FROM CB_2014_US_STATE_500K a2 CROSS JOIN CB_2014_US_COUNTY_500K a3

 WHERE a2.geom_orig.STIntersects(a3.geom_orig) = 1

(4576 rows affected)
SQL>

SELECT /* Join x34 ... x23intersections, pass through the computed areas, compute intersected area/higher resolution geolevel area,

	     compute maximum intersected area/higher resolution geolevel area using an analytic partition of all

	     duplicate higher resolution geolevels */

	       x12.CB_2014_US_NATION_5M,

	       x12.CB_2014_US_STATE_500K,

	       x23.CB_2014_US_COUNTY_500K,

	       CASE WHEN x12.a2_area > 0 THEN x12.a12_area/x12.a2_area ELSE NULL END test12,

	       MAX(x12.a12_area/x12.a2_area) OVER (PARTITION BY x12.CB_2014_US_STATE_500K) AS max12,

	       CASE WHEN x23.a3_area > 0 THEN x23.a23_area/x23.a3_area ELSE NULL END test23,

	       MAX(x23.a23_area/x23.a3_area) OVER (PARTITION BY x23.CB_2014_US_COUNTY_500K) AS max23

  INTO ##y_51

  FROM ##x12_51 x12, ##x23_51 x23

 WHERE x12.CB_2014_US_STATE_500K = x23.CB_2014_US_STATE_500K

(4576 rows affected)
SQL> DROP TABLE ##x12_51
SQL> DROP TABLE ##x23_51
SQL> INSERT INTO hierarchy_usa_2014 (cb_2014_us_nation_5m, cb_2014_us_state_500k, cb_2014_us_county_500k)

SELECT /* Select y intersection, eliminating duplicates using selecting the lower geolevel resolution

	 with the largest intersection by area for each (higher resolution) geolevel */

       cb_2014_us_nation_5m, cb_2014_us_state_500k, cb_2014_us_county_500k

  FROM ##y_51

 WHERE max12 = test12

   AND max12 > 0.5 /* >50% overlap */

   AND max23 = test23

   AND max23 > 0.5 /* >50% overlap */

 ORDER BY 1, 2, 3

(3233 rows affected)
SQL> DROP TABLE ##y_51
name
--------------------------------------------------------------------------------------------------------------------------------
#A0F47CB1
#A1614C43
#A1E8A0EA
#A2C2400E

(4 rows affected)
SQL> ALTER INDEX hierarchy_usa_2014_cb_2014_us_state_500k ON hierarchy_usa_2014 REORGANIZE
SQL> ALTER INDEX PK__hierarch__2848CBF7431166B7 ON hierarchy_usa_2014 REORGANIZE
SQL> UPDATE STATISTICS hierarchy_usa_2014

-- SQL statement 229: Check intersctions  for geograpy: usa_2014 >>>
DECLARE @l_geography AS VARCHAR(200)='USA_2014';
/*
 * SQL statement name: 	check_intersections.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geography; e.g. cb_2014_us_500k
 *
 * Description:			Check intersections
 * Note:				% becomes % after substitution
 */
--
	DECLARE c1 CURSOR FOR
		SELECT geography, hierarchytable
		  FROM geography_USA_2014
		 WHERE geography = @l_geography;
--
	DECLARE @geography 		AS VARCHAR(30);
	DECLARE @hierarchytable AS VARCHAR(200);
--
	DECLARE @CurrentUser	AS VARCHAR(60);
	DECLARE @function_name	AS VARCHAR(200);
	DECLARE @l_type			AS VARCHAR(30);
--
	DECLARE @e AS INTEGER=0;
	DECLARE @f AS INTEGER=0;
	DECLARE @g AS INTEGER=0;
BEGIN
--
	OPEN c1;
	FETCH c1 INTO @geography, @hierarchytable;
	CLOSE c1;
	DEALLOCATE c1;
--
	IF @geography IS NULL
		RAISERROR('geography: % not found', 16, 1, @l_geography	/* Geography */);
--
-- Call diff and multiple hierarchy tests
--
	SELECT @CurrentUser = user_name();
	SET @function_name=@CurrentUser + '.check_hierarchy_USA_2014';
	SET @l_type='missing';
	EXECUTE @function_name @geography, @hierarchytable, @l_type, @e;
	SET @l_type='spurious additional';
	EXECUTE @function_name @geography, @hierarchytable, @l_type, @f;
	SET @l_type='multiple hierarchy';
	EXECUTE @function_name @geography, @hierarchytable, @l_type, @g;
--
	IF @e+@f > 0
		RAISERROR('Geography: %s codes check %d missing, %d spurious additional, %d hierarchy fails', 16, 1,
			@geography	/* Geography */,
			@e			/* Missing */,
			@f			/* Spurious additional */,
			@g			/* Multiple hierarchy */);
	ELSE
		PRINT 'Geography: ' + @geography + ' codes check OK';
END;;

SQL> WITH /* missing */ a1 AS (

	SELECT COUNT(*) AS cb_2014_us_nation_5m_total

	  FROM (

		SELECT cb_2014_us_nation_5m FROM hierarchy_usa_2014

		EXCEPT

		SELECT cb_2014_us_nation_5m FROM lookup_cb_2014_us_nation_5m) as1)

, a2 AS (

	SELECT COUNT(*) AS cb_2014_us_state_500k_total

	  FROM (

		SELECT cb_2014_us_state_500k FROM hierarchy_usa_2014

		EXCEPT

		SELECT cb_2014_us_state_500k FROM lookup_cb_2014_us_state_500k) as2)

, a3 AS (

	SELECT COUNT(*) AS cb_2014_us_county_500k_total

	  FROM (

		SELECT cb_2014_us_county_500k FROM hierarchy_usa_2014

		EXCEPT

		SELECT cb_2014_us_county_500k FROM lookup_cb_2014_us_county_500k) as3)

SELECT CAST('cb_2014_us_nation_5m' AS VARCHAR) AS col,

	a1.cb_2014_us_nation_5m_total AS val

  FROM a1

UNION

SELECT CAST('cb_2014_us_state_500k' AS VARCHAR) AS col,

	a2.cb_2014_us_state_500k_total AS val

  FROM a2

UNION

SELECT CAST('cb_2014_us_county_500k' AS VARCHAR) AS col,

	a3.cb_2014_us_county_500k_total AS val

  FROM a3

(3 rows affected)
Geography: USA_2014 geolevel: cb_2014_us_nation_5m has 0 missing codes
Geography: USA_2014 geolevel: cb_2014_us_state_500k has 0 missing codes
Geography: USA_2014 geolevel: cb_2014_us_county_500k has 0 missing codes
SQL> WITH /* spurious additional */ a1 AS (

	SELECT COUNT(*) AS cb_2014_us_nation_5m_total

	  FROM (

		SELECT cb_2014_us_nation_5m FROM lookup_cb_2014_us_nation_5m

		EXCEPT

		SELECT cb_2014_us_nation_5m FROM hierarchy_usa_2014) as1)

, a2 AS (

	SELECT COUNT(*) AS cb_2014_us_state_500k_total

	  FROM (

		SELECT cb_2014_us_state_500k FROM lookup_cb_2014_us_state_500k

		EXCEPT

		SELECT cb_2014_us_state_500k FROM hierarchy_usa_2014) as2)

, a3 AS (

	SELECT COUNT(*) AS cb_2014_us_county_500k_total

	  FROM (

		SELECT cb_2014_us_county_500k FROM lookup_cb_2014_us_county_500k

		EXCEPT

		SELECT cb_2014_us_county_500k FROM hierarchy_usa_2014) as3)

SELECT CAST('cb_2014_us_nation_5m' AS VARCHAR) AS col,

	a1.cb_2014_us_nation_5m_total AS val

  FROM a1

UNION

SELECT CAST('cb_2014_us_state_500k' AS VARCHAR) AS col,

	a2.cb_2014_us_state_500k_total AS val

  FROM a2

UNION

SELECT CAST('cb_2014_us_county_500k' AS VARCHAR) AS col,

	a3.cb_2014_us_county_500k_total AS val

  FROM a3

(3 rows affected)
Geography: USA_2014 geolevel: cb_2014_us_nation_5m has 0 spurious additional codes
Geography: USA_2014 geolevel: cb_2014_us_state_500k has 0 spurious additional codes
Geography: USA_2014 geolevel: cb_2014_us_county_500k has 0 spurious additional codes
SQL> WITH /* multiple hierarchy */ a2 AS (

	SELECT COUNT(*) AS cb_2014_us_state_500k_total

	  FROM (

		SELECT cb_2014_us_state_500k, COUNT(DISTINCT(cb_2014_us_nation_5m)) AS total

		  FROM hierarchy_usa_2014

		 GROUP BY cb_2014_us_state_500k

		HAVING COUNT(DISTINCT(cb_2014_us_nation_5m)) > 1) as2)

, a3 AS (

	SELECT COUNT(*) AS cb_2014_us_county_500k_total

	  FROM (

		SELECT cb_2014_us_county_500k, COUNT(DISTINCT(cb_2014_us_state_500k)) AS total

		  FROM hierarchy_usa_2014

		 GROUP BY cb_2014_us_county_500k

		HAVING COUNT(DISTINCT(cb_2014_us_state_500k)) > 1) as3)

SELECT CAST('cb_2014_us_state_500k' AS VARCHAR) AS col,

	a2.cb_2014_us_state_500k_total AS val

  FROM a2

UNION

SELECT CAST('cb_2014_us_county_500k' AS VARCHAR) AS col,

	a3.cb_2014_us_county_500k_total AS val

  FROM a3

(2 rows affected)
Geography: USA_2014 geolevel: cb_2014_us_state_500k has 0 multiple hierarchy codes
Geography: USA_2014 geolevel: cb_2014_us_county_500k has 0 multiple hierarchy codes
Geography: USA_2014 codes check OK

--
-- Create geometry table
--

-- SQL statement 231: Drop geometry table geometry_usa_2014 >>>
IF OBJECT_ID('geometry_usa_2014', 'U') IS NOT NULL DROP TABLE geometry_usa_2014;


-- SQL statement 232: Create geometry table geometry_usa_2014 >>>
/*
 * SQL statement name: 	create_geometry_table.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. geometry_cb_2014_us_500k
 *						2: schema; e.g.rif_data. or ""
 *
 * Description:			Create geometry table
 * Note:				% becomes % after substitution
 */
CREATE TABLE geometry_usa_2014 (
	geolevel_id		INTEGER			NOT NULL,
	areaid			VARCHAR(200)	NOT NULL,
	zoomlevel		INTEGER			NOT NULL);


-- SQL statement 233: Add geom geometry column >>>
/*
 * SQL statement name: 	add_geometry_column2.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. geometry_cb_2014_us_500k
 *						2: column name; e.g. geom
 *						3: Column SRID; e.g. 4326 [NEVER USED IN SQL SERVER, set during WKT conversion]
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON [NEVER USED IN SQL SERVER]
 *                      5: Schema (rif_data. or "")
 *
 * Description:			Add *** geometry *** column to table
 * Note:				%% becomes % after substitution
 */
ALTER TABLE geometry_usa_2014 ADD geom geometry;


-- SQL statement 234: Add bbox geometry column >>>
/*
 * SQL statement name: 	add_geometry_column2.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. geometry_cb_2014_us_500k
 *						2: column name; e.g. geom
 *						3: Column SRID; e.g. 4326 [NEVER USED IN SQL SERVER, set during WKT conversion]
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON [NEVER USED IN SQL SERVER]
 *                      5: Schema (rif_data. or "")
 *
 * Description:			Add *** geometry *** column to table
 * Note:				%% becomes % after substitution
 */
ALTER TABLE geometry_usa_2014 ADD bbox geometry;


-- SQL statement 235: Comment geometry table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geometry_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geometry_usa_2014';
SELECT @columnName  = 'bbox';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Bounding box',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'bbox'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Bounding box',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'bbox';


-- SQL statement 236: Comment geometry table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geometry_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geometry_usa_2014';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'All geolevels geometry combined into a single table for a single geography',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'All geolevels geometry combined into a single table for a single geography',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014';


-- SQL statement 237: Comment geometry table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geometry_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geometry_usa_2014';
SELECT @columnName  = 'geolevel_id';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id';


-- SQL statement 238: Comment geometry table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geometry_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geometry_usa_2014';
SELECT @columnName  = 'zoomlevel';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Zoom level: 0 to maxoomlevel (11). Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at zoomlevel 11',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'zoomlevel'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Zoom level: 0 to maxoomlevel (11). Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at zoomlevel 11',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'zoomlevel';


-- SQL statement 239: Comment geometry table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geometry_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geometry_usa_2014';
SELECT @columnName  = 'areaid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'areaid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'areaid';


-- SQL statement 240: Comment geometry table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.geometry_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.geometry_usa_2014';
SELECT @columnName  = 'geom';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geometry data in SRID 4326 (WGS84).',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'geom'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geometry data in SRID 4326 (WGS84).',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'geometry_usa_2014',
		@level2type = N'Column', @level2name = 'geom';


--
-- Insert geometry table
--

-- SQL statement 242: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 3 geolevel_id,
       areaid,
        6 AS zoomlevel,
       geometry::STGeomFromWKB(geom_6.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_county_500k
ORDER BY 1, 3, 2;


(3233 rows affected)

-- SQL statement 243: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 3 geolevel_id,
       areaid,
        7 AS zoomlevel,
       geometry::STGeomFromWKB(geom_7.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_county_500k
ORDER BY 1, 3, 2;


(3233 rows affected)

-- SQL statement 244: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 3 geolevel_id,
       areaid,
        8 AS zoomlevel,
       geometry::STGeomFromWKB(geom_8.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_county_500k
ORDER BY 1, 3, 2;


(3233 rows affected)

-- SQL statement 245: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 3 geolevel_id,
       areaid,
        9 AS zoomlevel,
       geometry::STGeomFromWKB(geom_9.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_county_500k
ORDER BY 1, 3, 2;


(3233 rows affected)

-- SQL statement 246: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 1 geolevel_id,
       areaid,
        6 AS zoomlevel,
       geometry::STGeomFromWKB(geom_6.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_nation_5m
ORDER BY 1, 3, 2;


(1 rows affected)

-- SQL statement 247: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 1 geolevel_id,
       areaid,
        7 AS zoomlevel,
       geometry::STGeomFromWKB(geom_7.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_nation_5m
ORDER BY 1, 3, 2;


(1 rows affected)

-- SQL statement 248: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 1 geolevel_id,
       areaid,
        8 AS zoomlevel,
       geometry::STGeomFromWKB(geom_8.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_nation_5m
ORDER BY 1, 3, 2;


(1 rows affected)

-- SQL statement 249: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 1 geolevel_id,
       areaid,
        9 AS zoomlevel,
       geometry::STGeomFromWKB(geom_9.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_nation_5m
ORDER BY 1, 3, 2;


(1 rows affected)

-- SQL statement 250: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 2 geolevel_id,
       areaid,
        6 AS zoomlevel,
       geometry::STGeomFromWKB(geom_6.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_state_500k
ORDER BY 1, 3, 2;


(56 rows affected)

-- SQL statement 251: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 2 geolevel_id,
       areaid,
        7 AS zoomlevel,
       geometry::STGeomFromWKB(geom_7.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_state_500k
ORDER BY 1, 3, 2;


(56 rows affected)

-- SQL statement 252: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 2 geolevel_id,
       areaid,
        8 AS zoomlevel,
       geometry::STGeomFromWKB(geom_8.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_state_500k
ORDER BY 1, 3, 2;


(56 rows affected)

-- SQL statement 253: Insert into geometry table >>>
INSERT INTO geometry_usa_2014(geolevel_id, areaid, zoomlevel, geom)
SELECT 2 geolevel_id,
       areaid,
        9 AS zoomlevel,
       geometry::STGeomFromWKB(geom_9.STAsBinary(), 4326).MakeValid() AS geom
  FROM cb_2014_us_state_500k
ORDER BY 1, 3, 2;


(56 rows affected)

-- SQL statement 254: Update bounding box for implement PostGIS && operator >>>
/*
 * SQL statement name: 	geometry_bbox_update.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:
 *						1: Geometry table geometry_cb_2014_us_500k
 *
 * Description:			Update bbox column in geometry table using STEnvelope
 * Note:				% becomes % after substitution
 */

UPDATE geometry_usa_2014
   SET bbox = geom.STEnvelope()
 WHERE bbox IS NULL ;


(13160 rows affected)

--
-- No partitioning on SQL Server as it requires an Enterprise license; which
--

--
-- means you have to do it yourself using the generated scripts as a start.
--

-- SQL statement 257: Add primary key >>>
ALTER TABLE geometry_usa_2014 ADD PRIMARY KEY (geolevel_id, areaid, zoomlevel);


-- SQL statement 258: Create spatial index on geom >>>
/*
 * SQL statement name: 	create_spatial_geometry_index.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:
 *						1: index name;e.g. geometry_cb_2014_us_500k_gix
 *						2: table name; e.g. geometry_cb_2014_us_500k
 *						3: Geometry field name; e.g. geom
 *						4: Xmin (4326); e.g. -179.13729006727
 *						5: Ymin (4326); e.g. -14.3737802873213
 *						6: Xmax (4326); e.g.  179.773803959804
 *						7: Ymax (4326); e.g. 71.352561
 *
 * Description:			Create geometry table
 * Note:				% becomes % after substitution
 */
CREATE SPATIAL INDEX geometry_usa_2014_gix ON geometry_usa_2014 (geom)
	WITH ( BOUNDING_BOX = (xmin=-179.148909, ymin=-14.548699000000001, xmax=179.77847, ymax=71.36516200000001));


-- SQL statement 259: Create spatial index on bbox >>>
/*
 * SQL statement name: 	create_spatial_geometry_index.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:
 *						1: index name;e.g. geometry_cb_2014_us_500k_gix
 *						2: table name; e.g. geometry_cb_2014_us_500k
 *						3: Geometry field name; e.g. geom
 *						4: Xmin (4326); e.g. -179.13729006727
 *						5: Ymin (4326); e.g. -14.3737802873213
 *						6: Xmax (4326); e.g.  179.773803959804
 *						7: Ymax (4326); e.g. 71.352561
 *
 * Description:			Create geometry table
 * Note:				% becomes % after substitution
 */
CREATE SPATIAL INDEX geometry_usa_2014_gix2 ON geometry_usa_2014 (bbox)
	WITH ( BOUNDING_BOX = (xmin=-179.148909, ymin=-14.548699000000001, xmax=179.77847, ymax=71.36516200000001));


-- SQL statement 260: Analyze table >>>
UPDATE STATISTICS geometry_usa_2014;


-- SQL statement 261: Update areaid_count column in geolevels table using geometry table >>>
/*
 * SQL statement name: 	geolevels_areaid_update.sql
 * Type:				MS SQL Server SQL statement
 * Parameters:
 *						1: Geolevels table; e.g. geolevels_cb_2014_us_500k
 *						2: Geometry table geometry_cb_2014_us_500k
 *						3: Schema; e.g. rif_data. or ""
 *
 * Description:			Update areaid_count column in geolevels table using geometry table
 * Note:				% becomes % after substitution
 */
WITH b AS (
	SELECT geolevel_id, COUNT(DISTINCT(areaid)) AS areaid_count
	  FROM geometry_usa_2014
	 GROUP BY geolevel_id
)
UPDATE a
   SET areaid_count = b.areaid_count
  FROM geolevels_usa_2014 a
  JOIN b ON a.geolevel_id = b.geolevel_id;


(3 rows affected)

--
-- Adjacency table
--

-- SQL statement 263: Drop table adjacency_usa_2014 >>>
IF OBJECT_ID('adjacency_usa_2014', 'U') IS NOT NULL DROP TABLE adjacency_usa_2014;


-- SQL statement 264: Create table adjacency_usa_2014 >>>
/*
 * SQL statement name: 	create_adjacency_table.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: adjacency table; e.g. adjacency_cb_2014_us_500k
 *						2: schema; e.g.rif_data. or ""
 *
 * Description:			Create adjacency table
 * Note:				% becomes % after substitution
 */
CREATE TABLE adjacency_usa_2014 (
	geolevel_id		INTEGER			NOT NULL,
	areaid			VARCHAR(200)	NOT NULL,
	num_adjacencies INTEGER			NOT NULL,
	adjacency_list	VARCHAR(8000)	NOT NULL,
	CONSTRAINT adjacency_usa_2014_pk PRIMARY KEY (geolevel_id, areaid)
);


-- SQL statement 265: Comment table: adjacency_usa_2014 >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.adjacency_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.adjacency_usa_2014';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Adjacency lookup table for US 2014 Census geography to county level',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Adjacency lookup table for US 2014 Census geography to county level',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014';


-- SQL statement 266: Comment column: adjacency_usa_2014.geolevel_id >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.adjacency_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.adjacency_usa_2014';
SELECT @columnName  = 'geolevel_id';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id';


-- SQL statement 267: Comment column: adjacency_usa_2014.areaid >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.adjacency_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.adjacency_usa_2014';
SELECT @columnName  = 'areaid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area Id',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014',
		@level2type = N'Column', @level2name = 'areaid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area Id',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014',
		@level2type = N'Column', @level2name = 'areaid';


-- SQL statement 268: Comment column: adjacency_usa_2014.num_adjacencies >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.adjacency_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.adjacency_usa_2014';
SELECT @columnName  = 'num_adjacencies';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Number of adjacencies',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014',
		@level2type = N'Column', @level2name = 'num_adjacencies'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Number of adjacencies',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014',
		@level2type = N'Column', @level2name = 'num_adjacencies';


-- SQL statement 269: Comment column: adjacency_usa_2014.adjacency_list >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.adjacency_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.adjacency_usa_2014';
SELECT @columnName  = 'adjacency_list';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Adjacent area Ids',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014',
		@level2type = N'Column', @level2name = 'adjacency_list'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Adjacent area Ids',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'adjacency_usa_2014',
		@level2type = N'Column', @level2name = 'adjacency_list';


-- SQL statement 270: Insert into adjacency_usa_2014 >>>
/*
 * SQL statement name: 	insert_adjacency.sql
 * Type:				Microsoft SQL Server SQL
 * Parameters:
 *						1: adjacency table; e.g. adjacency_cb_2014_us_500k
 *						2: geometry table; e.g. geometry_cb_2014_us_500k
 *						3: Max zoomlevel
 *
 * Description:			Create insert statement into adjacency table
 * Note:				%% becomes % after substitution
 */
WITH a AS (
	SELECT a.geolevel_id, a.areaid, b.areaid AS adjacent_areaid
	  FROM geometry_usa_2014 a, geometry_usa_2014 b
	 WHERE a.zoomlevel                 = 9
	   AND b.zoomlevel                 = 9
	   AND a.geolevel_id               = b.geolevel_id
	   AND a.areaid                    != b.areaid
	   AND a.geom.STIntersects(b.geom) = 1
), b AS (
	SELECT a.geolevel_id, a.areaid,
		   c.adjacency_list
	  FROM a OUTER APPLY (
		SELECT STUFF(( SELECT ',' + b.adjacent_areaid
		   FROM a AS b
		  WHERE a.areaid      = b.areaid
			AND a.geolevel_id = b.geolevel_id
		  ORDER BY b.adjacent_areaid
			FOR XML PATH('') ), 1,1,'') AS adjacency_list) AS c
)
INSERT INTO adjacency_usa_2014(geolevel_id, areaid, num_adjacencies, adjacency_list)
SELECT DISTINCT geolevel_id, areaid, LEN(adjacency_list)-LEN(REPLACE(adjacency_list, ',', ''))+1 AS num_adjacencies, adjacency_list
  FROM b
 ORDER BY 1, 2;


(3262 rows affected)

--
-- Create tiles functions
--

-- SQL statement 272: Create function: longitude2tile.sql >>>
/*
 * SQL statement name: 	longitude2tile.sql
 * Type:				Postgres/PostGIS PL/pgsql function
 * Parameters:			None
 *
 * Description:			Convert longitude (WGS84 - 4326) to OSM tile x
 * Note:				% becomes % after substitution
 */
IF OBJECT_ID (N'tileMaker_longitude2tile', N'FN') IS NOT NULL
    DROP FUNCTION tileMaker_longitude2tile;


CREATE FUNCTION tileMaker_longitude2tile(@longitude DOUBLE PRECISION, @zoom_level INTEGER)
RETURNS INTEGER AS
BEGIN
	DECLARE @tileX INTEGER;
	SET @tileX=CAST(
			FLOOR( (@longitude + 180) / 360 * POWER(2, @zoom_level) ) AS INTEGER);
	RETURN @tileX;
END;


DECLARE @CurrentUser sysname;
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty  'MS_Description', 'Function: 	 tileMaker_longitude2tile()
Parameters:	 Longitude, zoom level
Returns:	 OSM Tile x
Description: Convert longitude (WGS84 - 4326) to OSM tile x

Derivation of the tile X/Y

* Reproject the coordinates to the Mercator projection (from EPSG:4326 to EPSG:3857):

x = lon
y = arsinh(tan(lat)) = log[tan(lat) + sec(lat)]
(lat and lon are in radians)

* Transform range of x and y to 0 � 1 and shift origin to top left corner:

x = [1 + (x / p)] / 2
y = [1 - (y / p)] / 2

* Calculate the number of tiles across the map, n, using 2**zoom
* Multiply x and y by n. Round results down to give tilex and tiley.
',
   'user', @CurrentUser,
   'function', 'tileMaker_longitude2tile';


-- SQL statement 273: Create function: latitude2tile.sql >>>
/*
 * SQL statement name: 	latitude2tile.sql
 * Type:				Microsoft SQL Server T/sql function
 * Parameters:			None
 *
 * Description:			Convert latitude (WGS84 - 4326) to OSM tile y
 * Note:				% becomes % after substitution
 */
IF OBJECT_ID (N'tileMaker_latitude2tile', N'FN') IS NOT NULL
    DROP FUNCTION tileMaker_latitude2tile;


CREATE FUNCTION tileMaker_latitude2tile(@latitude DOUBLE PRECISION, @zoom_level INTEGER)
RETURNS INTEGER
AS
BEGIN
	DECLARE @tileY INTEGER;
	SET @tileY=CAST(
					FLOOR(
						(1.0 - LOG /* Natural Log */
							(TAN(RADIANS(@latitude)) + 1.0 / COS(RADIANS(@latitude))) / PI()) / 2.0 * POWER(2, @zoom_level)
						)
					AS INTEGER);
	RETURN @tileY;
END;


DECLARE @CurrentUser sysname;
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty  'MS_Description', 'Function: 	 tileMaker_latitude2tile()
Parameters:	 Latitude, zoom level
Returns:	 OSM Tile y
Description: Convert latitude (WGS84 - 4326) to OSM tile x

Derivation of the tile X/Y

* Reproject the coordinates to the Mercator projection (from EPSG:4326 to EPSG:3857):

x = lon
y = arsinh(tan(lat)) = log[tan(lat) + sec(lat)]
(lat and lon are in radians)

* Transform range of x and y to 0 � 1 and shift origin to top left corner:

x = [1 + (x / p)] / 2
y = [1 - (y / p)] / 2

* Calculate the number of tiles across the map, n, using 2**zoom
* Multiply x and y by n. Round results down to give tilex and tiley.
',
   'user', @CurrentUser,
   'function', 'tileMaker_latitude2tile';


-- SQL statement 274: Create function: tile2longitude.sql >>>
/*
 * SQL statement name: 	tile2longitude.sql
 * Type:				Postgres/PostGIS PL/pgsql function
 * Parameters:			None
 *
 * Description:			Convert OSM tile x to longitude (WGS84 - 4326)
 * Note:				% becomes % after substitution
 */
IF OBJECT_ID (N'tileMaker_tile2longitude', N'FN') IS NOT NULL
    DROP FUNCTION tileMaker_tile2longitude;


CREATE FUNCTION tileMaker_tile2longitude(@x INTEGER, @zoom_level INTEGER)
RETURNS DOUBLE PRECISION AS
BEGIN
	DECLARE @longitude DOUBLE PRECISION;
	SET @longitude=CAST( ( (@x * 1.0) / POWER(2, @zoom_level) * 360.0) - 180.0 AS DOUBLE PRECISION);
	RETURN @longitude;
END;


DECLARE @CurrentUser sysname;
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty  'MS_Description', 'Function: 	 tileMaker_tile2longitude()
Parameters:	 OSM Tile x, zoom level
Returns:	 Longitude
Description: Convert OSM tile x to longitude (WGS84 - 4326)
',
   'user', @CurrentUser,
   'function', 'tileMaker_tile2longitude';


-- SQL statement 275: Create function: tile2latitude.sql >>>
/*
 * SQL statement name: 	tileMaker_tile2latitude.sql
 * Type:				Postgres/PostGIS PL/pgsql function
 * Parameters:			None
 *
 * Description:			Convert OSM tile y to latitude (WGS84 - 4326)
 * Note:				% becomes % after substitution
 */
IF OBJECT_ID (N'tileMaker_tile2latitude', N'FN') IS NOT NULL
    DROP FUNCTION tileMaker_tile2latitude;


CREATE FUNCTION tileMaker_tile2latitude(@y INTEGER, @zoom_level INTEGER)
RETURNS DOUBLE PRECISION AS
BEGIN
	DECLARE @latitude DOUBLE PRECISION;
	DECLARE @n FLOAT;
	DECLARE @sinh FLOAT;
	DECLARE @E FLOAT = 2.7182818284;

    SET @n = PI() - (2.0 * PI() * @y) / POWER(2.0, @zoom_level);
    SET @sinh = (1 - POWER(@E, -2*@n)) / (2 * POWER(@E, -@n));
    SET @latitude = DEGREES(ATAN(@sinh));
	RETURN @latitude;
END;


DECLARE @CurrentUser sysname;
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty  'MS_Description', 'Function: 	 tileMaker_tile2latitude()
Parameters:	 OSM Tile y, zoom level
Returns:	 Latitude
Description: Convert OSM tile y to latitude (WGS84 - 4326)
',
   'user', @CurrentUser,
   'function', 'tileMaker_tile2latitude';


-- SQL statement 276: Tile check >>>
/*
 * SQL statement name: 	tile_check.sql
 * Type:				MS SQL Server function
 * Parameters:
 *						1: Lowest resolution geolevels table
 *						2: Geography
 *						3: min_zoomlevel
 *						4: max_zoomlevel
 *						5: Geolevel id = 1 geometry table
 *
 * Description:			Convert OSM tile y to latitude (WGS84 - 4326)
 * Note:				% becomes % after substitution
 */
WITH a AS ( /* Geolevel summary */
		SELECT a1.geography,
		       a1.geolevel_name AS min_geolevel_name,
               MIN(geolevel_id) AS min_geolevel_id,
               CAST(9 AS INTEGER) AS zoomlevel,
               a2.max_geolevel_id
          FROM geolevels_usa_2014 a1, (
                        SELECT geography, MAX(geolevel_id) AS max_geolevel_id
  						  FROM geolevels_usa_2014
						 GROUP BY geography
						) a2
         WHERE a1.geography     = 'USA_2014'
           AND a1.geography     = a2.geography
         GROUP BY a1.geography, a1.geolevel_name, a2.max_geolevel_id
        HAVING MIN(geolevel_id) = 1
), b AS ( /* Get bounds of geography */
	SELECT a2.geography,
		   a2.min_geolevel_id,
		   a2.max_geolevel_id,
		   a2.zoomlevel,
		   CASE
				WHEN a2.zoomlevel <= 6 THEN
					geometry::STGeomFromWKB(b.geom_6.STAsBinary(), b.geom_6.STSrid /* Cast to geometry */).STEnvelope()
				WHEN a2.zoomlevel BETWEEN (6+1) AND 9 THEN
					geometry::STGeomFromWKB(b.geom_9.STAsBinary(), b.geom_9.STSrid /* Cast to geometry */).STEnvelope()
				ELSE NULL
           END AS geom_envelope
      FROM cb_2014_us_nation_5m b, a a2
)
SELECT b.geography,
	   b.min_geolevel_id,
	   b.max_geolevel_id,
	   b.zoomlevel,
	   CAST(b.geom_envelope.STPointN(1).STX AS numeric(8,5)) AS Xmin,
	   CAST(b.geom_envelope.STPointN(3).STX AS numeric(8,5)) AS Xmax,
	   CAST(b.geom_envelope.STPointN(1).STY AS numeric(8,5)) AS Ymin,
	   CAST(b.geom_envelope.STPointN(3).STY AS numeric(8,5)) AS Ymax,
	   peter.tileMaker_latitude2tile(b.geom_envelope.STPointN(1).STY, zoomlevel) AS Y_mintile,
	   peter.tileMaker_latitude2tile(b.geom_envelope.STPointN(3).STY, zoomlevel) AS Y_maxtile,
	   peter.tileMaker_longitude2tile(b.geom_envelope.STPointN(1).STX, zoomlevel) AS X_mintile,
	   peter.tileMaker_longitude2tile(b.geom_envelope.STPointN(3).STX, zoomlevel) AS X_maxtile
  FROM b;

geography                                          min_geolevel_id max_geolevel_id zoomlevel   Xmin       Xmax       Ymin       Ymax       Y_mintile   Y_maxtile   X_mintile   X_maxtile
-------------------------------------------------- --------------- --------------- ----------- ---------- ---------- ---------- ---------- ----------- ----------- ----------- -----------
USA_2014                                                         1               3           9 -179.14734  179.77847  -14.55255   71.35256         276         108           1         511

(1 rows affected)

--
-- Create tiles tables
--

-- SQL statement 278: Drop table t_tiles_usa_2014 >>>
IF OBJECT_ID('t_tiles_usa_2014', 'U') IS NOT NULL DROP TABLE t_tiles_usa_2014;


-- SQL statement 279: Create tiles table >>>
/*
 * SQL statement name: 	create_tiles_table.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. t_tiles_cb_2014_us_county_500k
 *						2: JSON datatype (Postgres JSON, SQL server Text)
 *						3: Schema; e.g. rif_data. or ""
 *
 * Description:			Create tiles table
 * Note:				%% becomes % after substitution
 */
CREATE TABLE t_tiles_usa_2014 (
	geolevel_id			INTEGER			NOT NULL,
	zoomlevel			INTEGER			NOT NULL,
	x					INTEGER			NOT NULL,
	y					INTEGER			NOT NULL,
	optimised_topojson	NVARCHAR(MAX),
	tile_id				VARCHAR(200)	NOT NULL,
	areaid_count		INTEGER			NOT NULL,
	PRIMARY KEY (tile_id));


-- SQL statement 280: Comment tiles table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.t_tiles_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.t_tiles_usa_2014';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Maptiles for geography; empty tiles are added to complete zoomlevels for zoomlevels 0 to 11',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Maptiles for geography; empty tiles are added to complete zoomlevels for zoomlevels 0 to 11',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014';


-- SQL statement 281: Comment tiles table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.t_tiles_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.t_tiles_usa_2014';
SELECT @columnName  = 'geolevel_id';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id';


-- SQL statement 282: Comment tiles table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.t_tiles_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.t_tiles_usa_2014';
SELECT @columnName  = 'zoomlevel';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Zoom level: 0 to 11. Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at zoomlevel 11',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'zoomlevel'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Zoom level: 0 to 11. Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at zoomlevel 11',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'zoomlevel';


-- SQL statement 283: Comment tiles table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.t_tiles_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.t_tiles_usa_2014';
SELECT @columnName  = 'x';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'X tile number. From 0 to (2**<zoomlevel>)-1',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'x'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'X tile number. From 0 to (2**<zoomlevel>)-1',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'x';


-- SQL statement 284: Comment tiles table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.t_tiles_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.t_tiles_usa_2014';
SELECT @columnName  = 'y';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Y tile number. From 0 to (2**<zoomlevel>)-1',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'y'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Y tile number. From 0 to (2**<zoomlevel>)-1',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'y';


-- SQL statement 285: Comment tiles table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.t_tiles_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.t_tiles_usa_2014';
SELECT @columnName  = 'optimised_topojson';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Tile multipolygon in TopoJSON format, optimised for zoomlevel N. The SRID is always 4326.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'optimised_topojson'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Tile multipolygon in TopoJSON format, optimised for zoomlevel N. The SRID is always 4326.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'optimised_topojson';


-- SQL statement 286: Comment tiles table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.t_tiles_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.t_tiles_usa_2014';
SELECT @columnName  = 'tile_id';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Tile ID in the format <geolevel number>_<geolevel name>_<zoomlevel>_<X tile number>_<Y tile number>',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'tile_id'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Tile ID in the format <geolevel number>_<geolevel name>_<zoomlevel>_<X tile number>_<Y tile number>',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'tile_id';


-- SQL statement 287: Comment tiles table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.t_tiles_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.t_tiles_usa_2014';
SELECT @columnName  = 'areaid_count';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Total number of areaIDs (geoJSON features)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'areaid_count'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Total number of areaIDs (geoJSON features)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 't_tiles_usa_2014',
		@level2type = N'Column', @level2name = 'areaid_count';


-- SQL statement 288: Add tiles index: t_tiles_usa_2014_x_tile >>>
CREATE INDEX t_tiles_usa_2014_x_tile ON t_tiles_usa_2014 (geolevel_id, zoomlevel, x);


-- SQL statement 289: Add tiles index: t_tiles_usa_2014_y_tile >>>
CREATE INDEX t_tiles_usa_2014_y_tile ON t_tiles_usa_2014 (geolevel_id, zoomlevel, x);


-- SQL statement 290: Add tiles index: t_tiles_usa_2014_xy_tile >>>
CREATE INDEX t_tiles_usa_2014_xy_tile ON t_tiles_usa_2014 (geolevel_id, zoomlevel, x, y);


-- SQL statement 291: Add tiles index: t_tiles_usa_2014_areaid_count >>>
CREATE INDEX t_tiles_usa_2014_areaid_count ON t_tiles_usa_2014 (areaid_count);


-- SQL statement 292: Create tiles view >>>
/*
 * SQL statement name: 	create_tiles_view.sql
 * Type:				Microsoft SQL Server SQL statement
 * Parameters:
 *						1: tiles view; e.g. tiles_cb_2014_us_county_500k
 *						2: geolevel table; e.g. geolevels_cb_2014_us_county_500k
 *						3: JSON datatype (Postgres JSON, SQL server VARCHAR) [No longer used]
 *						4: tiles table; e.g. t_tiles_cb_2014_us_500k
 *  					5: Max zoomlevel; e.g. 11
 *						6: Data schema; e.g. rif_data. or ""
 *						7: RIF or user schema; e.g. $(SQLCMDUSER) or rif40
 *						8: Geography; e.g. USA_2014
 *
 * Description:			Create tiles view
 * Note:				%% becomes % after substitution
 */
CREATE VIEW tiles_usa_2014 AS
WITH a AS (
        SELECT geography,
               MAX(geolevel_id) AS max_geolevel_id
          FROM peter.geolevels_usa_2014
		 WHERE geography = 'USA_2014'
         GROUP BY geography
), b AS (
		SELECT a.geography, z.IntValue AS geolevel_id
		  FROM a CROSS APPLY peter.generate_series(0, CAST(a.max_geolevel_id AS INTEGER), 1) z
), c AS (
        SELECT b2.geolevel_name,
               b.geolevel_id,
               b.geography,
			   b2.areaid_count
          FROM b, peter.geolevels_usa_2014 b2
		 WHERE b.geolevel_id = b2.geolevel_id
		   AND b.geography   = b2.geography
), d AS (
        SELECT z.IntValue AS zoomlevel
		  FROM peter.generate_series(0, 9, 1) z /* RIF or user schema; e.g. $(SQLCMDUSER) or rif40 */
), ex AS (
        SELECT d.zoomlevel, z.IntValue AS xy_series
          FROM d CROSS APPLY peter.generate_series(0, CAST(POWER(2, d.zoomlevel) AS INTEGER) - 1, 1) z
), ey AS (
        SELECT c.geolevel_name,
			   c.areaid_count,
               c.geolevel_id,
               c.geography,
               ex.zoomlevel,
               ex.xy_series
          FROM c,
               ex
)
SELECT z.geography,
       z.geolevel_id,
       z.geolevel_name,
       CASE
            WHEN h1.tile_id IS NULL AND h2.tile_id IS NULL THEN 1
            ELSE 0
       END AS no_area_ids,
       COALESCE(h1.tile_id,
				CAST(z.geolevel_id AS VARCHAR) +
					'_' +
					z.geolevel_name +
					'_' +
					CAST(z.zoomlevel AS VARCHAR) +
					'_' +
					CAST(z.x AS VARCHAR) +
					'_' +
					CAST(z.y AS VARCHAR)
				) AS tile_id,
       z.x,
       z.y,
       z.zoomlevel,
       COALESCE(h1.optimised_topojson,
				h2.optimised_topojson,
				'{"type": "FeatureCollection","features":[]}' /* NULL geojson */) AS optimised_topojson
  FROM (
		SELECT ey.geolevel_name,
			   ey.areaid_count,
               ey.geolevel_id,
               ey.geography,
               ex.zoomlevel,
               ex.xy_series AS x,
               ey.xy_series AS y
          FROM ey, ex /* Cross join */
         WHERE ex.zoomlevel = ey.zoomlevel
		) z
		 LEFT JOIN t_tiles_usa_2014 h1 ON ( /* Multiple area ids in the geolevel */
				z.areaid_count > 1 AND
				z.zoomlevel    = h1.zoomlevel AND
				z.x            = h1.x AND
				z.y            = h1.y AND
				z.geolevel_id  = h1.geolevel_id)
		 LEFT JOIN t_tiles_usa_2014 h2 ON ( /* Single area ids in the geolevel */
				z.areaid_count = 1 AND
				h2.zoomlevel   = 0 AND
				h2.x           = 0 AND
				h2.y           = 0 AND
				h2.geolevel_id = 1);


-- SQL statement 293: Comment tiles view >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment view
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'Maptiles view for geography; empty tiles are added to complete zoomlevels for zoomlevels 0 to 11. This view is efficent!',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014'   ;


-- SQL statement 294: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'Geography',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'geography';


-- SQL statement 295: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'geolevel_id';


-- SQL statement 296: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'Zoom level: 0 to 11. Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at zoomlevel 11',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'zoomlevel';


-- SQL statement 297: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'X tile number. From 0 to (2**<zoomlevel>)-1',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'x';


-- SQL statement 298: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'Y tile number. From 0 to (2**<zoomlevel>)-1',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'y';


-- SQL statement 299: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'Tile multipolygon in TopoJSON format, optimised for zoomlevel N. The SRID is always 4326.',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'optimised_topojson';


-- SQL statement 300: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'Tile ID in the format <geolevel number>_<geolevel name>_<zoomlevel>_<X tile number>_<Y tile number>',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'tile_id';


-- SQL statement 301: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'Name of geolevel. This will be a column name in the numerator/denominator tables',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'geolevel_name';


-- SQL statement 302: Comment tiles view column >>>
DECLARE @CurrentUser sysname /*
 * SQL statement name: 	comment_view_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: view; e.g. tiles_cb_2014_us_500k
 *						2: column; e.g. geography
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty
@name = N'MS_Description',
@value = N'Tile contains no area_ids flag: 0/1',
@level0type = N'Schema', @level0name = @CurrentUser,
@level1type = N'View', @level1name = 'tiles_usa_2014',
@level2type = N'Column', @level2name = 'no_area_ids';


--
-- Create tile limits table
--

-- SQL statement 304: Create tileMaker_STMakeEnvelope() >>>
/*
 * SQL statement name: 	tileMaker_STMakeEnvelope.sql
 * Type:				MS SQL Server SQL
 * Parameters:			None
 * Description:			geometry  ST_MakeEnvelope(double precision xmin, double precision ymin, double precision xmax,
 *						double precision ymax, integer srid=4326);
 * Note:				% becomes % after substitution
 *
 *  zoomlevel |         xmin     |         xmax     |          ymin     |      ymax |
 * -----------+------------------+------------------+-------------------+-----------+
 *          0 | -179.13729006727 | 179.773803959804 | -14.3737802873213 | 71.352561 |
 * WITH a AS (
 *	SELECT ST_MakeEnvelope(-179.13729006727, -14.373780287321, 179.773803959804, 71.352561, 4326) AS bbox
 * )
 * SELECT ST_AsText(a.bbox) AS bbox
 *   FROM a;
 *                                                                               bbox
 * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
 *  POLYGON((-179.13729006727 -14.373780287321,-179.13729006727 71.352561,179.773803959804 71.352561,179.773803959804 -14.373780287321,-179.13729006727 -14.373780287321))
 * (1 row)
 *
 *  POLYGON((xmin ymin,xmin ymax,xmax ymax,xmax ymin,xmin ymin))
 */
IF OBJECT_ID (N'tileMaker_STMakeEnvelope', N'FN') IS NOT NULL
    DROP FUNCTION tileMaker_STMakeEnvelope;


CREATE FUNCTION tileMaker_STMakeEnvelope(@xmin DOUBLE PRECISION, @ymin DOUBLE PRECISION, @xmax DOUBLE PRECISION, @ymax DOUBLE PRECISION, @srid INTEGER=4326)
RETURNS GEOMETRY AS
BEGIN
	DECLARE @geom GEOMETRY;
	SET @geom=geometry::STGeomFromText('POLYGON(('+
	CAST(@xmin AS VARCHAR) + ' ' +
	CAST(@ymin AS VARCHAR) + ',' +
	CAST(@xmin AS VARCHAR) + ' ' +
	CAST(@ymax AS VARCHAR) + ',' +
	CAST(@xmax AS VARCHAR) + ' ' +
	CAST(@ymax AS VARCHAR) + ',' +
	CAST(@xmax AS VARCHAR) + ' ' +
	CAST(@ymin AS VARCHAR) + ',' +
	CAST(@xmin AS VARCHAR) + ' ' +
	CAST(@ymin AS VARCHAR) + '))', @srid);
	RETURN @geom;
END;


DECLARE @CurrentUser sysname;
SELECT @CurrentUser = user_name();
EXECUTE sp_addextendedproperty  'MS_Description', 'Function: 	 tileMaker_STMakeEnvelope()
Parameters:	 double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=4326
Returns:	 Geometry
Description: Creates a rectangular Polygon formed from the given minimums and maximums. Input values must be in the
			 spatial reference system specified by the SRID.

Creates a rectangular Polygon formed from the minima and maxima. by the given shell. Input values must be in SRS specified
by the SRID. If no SRID is specified the WGS 84 spatial reference system is assumed
',
   'user', @CurrentUser,
   'function', 'tileMaker_STMakeEnvelope' ;


-- SQL statement 305: Drop table tile_limits_usa_2014 >>>
IF OBJECT_ID('tile_limits_usa_2014', 'U') IS NOT NULL DROP TABLE tile_limits_usa_2014;


-- SQL statement 306: Create table tile_limits_usa_2014 >>>
/*
 * SQL statement name: 	create_tile_limits_table.sql
 * Type:				MS SQL Server SQL
 * Parameters:
 *						1: Tile limits table; e.g. tile_limits_cb_2014_us_500k
 *						2: Geometry table; e.g. geometry_cb_2014_us_500k
 *						3: max_zoomlevel
 *
 * Description:			Create tile limits table
 * Note:				% becomes % after substitution
 */
WITH a AS (
	SELECT z.IntValue AS zoomlevel
	  FROM peter.generate_series(0, 9, 1) z
), b AS ( /* Get bounds of geography */
        SELECT a.zoomlevel,
			   geometry::EnvelopeAggregate(b.geom).STPointN(1).STX AS Xmin,
			   geometry::EnvelopeAggregate(b.geom).STPointN(1).STY AS Ymin,
			   geometry::EnvelopeAggregate(b.geom).STPointN(3).STX AS Xmax,
			   geometry::EnvelopeAggregate(b.geom).STPointN(3).STY AS Ymax
      FROM a
			LEFT OUTER JOIN geometry_usa_2014 b ON (b.geolevel_id = 1 AND a.zoomlevel = b.zoomlevel)
	 GROUP BY a.zoomlevel
), c AS (
        SELECT b.zoomlevel,
			   geometry::EnvelopeAggregate(b.geom).STPointN(1).STX AS Xmin,
			   geometry::EnvelopeAggregate(b.geom).STPointN(1).STY AS Ymin,
			   geometry::EnvelopeAggregate(b.geom).STPointN(3).STX AS Xmax,
			   geometry::EnvelopeAggregate(b.geom).STPointN(3).STY AS Ymax
      FROM geometry_usa_2014 b
	 WHERE b.geolevel_id  = 1
	   AND b.zoomlevel = 6
	 GROUP BY b.zoomlevel
), d AS ( /* Convert XY bounds to tile numbers */
        SELECT b.zoomlevel,
               COALESCE(b.Xmin, c.Xmin) AS x_min,
			   COALESCE(b.Xmax, c.Xmax) AS x_max,
			   COALESCE(b.Ymin, c.Ymin) AS y_min,
			   COALESCE(b.Ymax, c.Ymax) AS y_max,
               peter.tileMaker_latitude2tile(COALESCE(b.Ymax, c.Ymax), b.zoomlevel) AS Y_mintile,
               peter.tileMaker_latitude2tile(COALESCE(b.Ymin, c.Ymin), b.zoomlevel) AS Y_maxtile,
               peter.tileMaker_longitude2tile(COALESCE(b.Xmin, c.Xmin), b.zoomlevel) AS X_mintile,
               peter.tileMaker_longitude2tile(COALESCE(b.Xmax, c.Xmax), b.zoomlevel) AS X_maxtile
      FROM b, c
)
SELECT d.*,
       peter.tileMaker_STMakeEnvelope(d.x_min, d.y_min, d.x_max, d.y_max, 4326) AS bbox
  INTO tile_limits_usa_2014
  FROM d;


(10 rows affected)

-- SQL statement 307: Comment tile limits table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Tile limits',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Tile limits',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014';


-- SQL statement 308: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'zoomlevel';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Zoom level: 0 to 11. Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at max zooomlevel (11)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'zoomlevel'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Zoom level: 0 to 11. Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at max zooomlevel (11)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'zoomlevel';


-- SQL statement 309: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'x_min';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Min X (longitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'x_min'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Min X (longitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'x_min';


-- SQL statement 310: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'x_max';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Max X (longitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'x_max'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Max X (longitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'x_max';


-- SQL statement 311: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'y_min';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Min Y (latitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'y_min'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Min Y (latitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'y_min';


-- SQL statement 312: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'y_max';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Max Y (latitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'y_max'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Max Y (latitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'y_max';


-- SQL statement 313: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'y_mintile';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Min Y tile number (latitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'y_mintile'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Min Y tile number (latitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'y_mintile';


-- SQL statement 314: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'y_maxtile';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Max Y tile number (latitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'y_maxtile'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Max Y tile number (latitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'y_maxtile';


-- SQL statement 315: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'x_mintile';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Min X tile number (longitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'x_mintile'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Min X tile number (longitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'x_mintile';


-- SQL statement 316: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'x_maxtile';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Max X tile number (longitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'x_maxtile'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Max X tile number (longitude)',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'x_maxtile';


-- SQL statement 317: Comment tile limits table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_limits_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_limits_usa_2014';
SELECT @columnName  = 'bbox';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Bounding box polygon for geolevel_id 1 area',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'bbox'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Bounding box polygon for geolevel_id 1 area',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_limits_usa_2014',
		@level2type = N'Column', @level2name = 'bbox';


-- SQL statement 318: Make primary key not null >>>
/*
 * SQL statement name: 	not_null.sql
 * Type:				MS SQL Server SQL
 * Parameters:
 *						1: Tile limits table; e.g. tile_limits_cb_2014_us_500k
 *						2: not null column; e.g. zoomlevel
 *
 * Description:			Make column not null
 * Note:				% becomes % after substitution
 */
ALTER TABLE tile_limits_usa_2014 ALTER COLUMN zoomlevel INTEGER NOT NULL;


-- SQL statement 319: Add primary key >>>
ALTER TABLE tile_limits_usa_2014 ADD PRIMARY KEY (zoomlevel);


-- SQL statement 320: Analyze table >>>
UPDATE STATISTICS tile_limits_usa_2014;


-- SQL statement 321: Analyze table >>>
SELECT zoomlevel, x_min, x_max, y_min, y_max, y_mintile, y_maxtile, x_mintile, x_maxtile FROM tile_limits_usa_2014;

zoomlevel   x_min                    x_max                    y_min                    y_max                    y_mintile   y_maxtile   x_mintile   x_maxtile
----------- ------------------------ ------------------------ ------------------------ ------------------------ ----------- ----------- ----------- -----------
          0      -179.14734000000004       179.77846999999986      -14.549542318143596       71.352561000000122           0           0           0           0
          1      -179.14734000000004       179.77846999999986      -14.549542318143596       71.352561000000122           0           1           0           1
          2      -179.14734000000004       179.77846999999986      -14.549542318143596       71.352561000000122           0           2           0           3
          3      -179.14734000000004       179.77846999999986      -14.549542318143596       71.352561000000122           1           4           0           7
          4      -179.14734000000004       179.77846999999986      -14.549542318143596       71.352561000000122           3           8           0          15
          5      -179.14734000000004       179.77846999999986      -14.549542318143596       71.352561000000122           6          17           0          31
          6      -179.14734000000004       179.77846999999986      -14.549542318143596       71.352561000000122          13          34           0          63
          7      -179.14734000000053       179.77846999999991      -14.549542318143029       71.352561000000094          27          69           0         127
          8      -179.14734000000036        179.7784700000004      -14.552548999999976       71.352560999999994          54         138           0         255
          9      -179.14734000000013       179.77847000000025      -14.552549000000058       71.352561000000009         108         276           1         511

(10 rows affected)

-- SQL statement 322: Drop table tile_intersects_usa_2014 >>>
IF OBJECT_ID('tile_intersects_usa_2014', 'U') IS NOT NULL DROP TABLE tile_intersects_usa_2014;


-- SQL statement 323: Create tile intersects table >>>
/*
 * SQL statement name: 	create_tile_intersects_table.sql
 * Type:				Common SQL statement
 * Parameters:
 *						1: table; e.g. tile_intersects_cb_2014_us_500k
 *						2: JSON datatype (Postgres: JSON, MS SQL Server: Text)
 *						3: ST_Within()/STWithin() return datatype: bit (SQL Server: 0/1) or BOOLEAN (Postgres)
 *
 * Description:			Create tile intersects table
 * Note:				% becomes % after substitution
 */
CREATE TABLE tile_intersects_usa_2014 (
	geolevel_id				INTEGER			NOT NULL,
	zoomlevel				INTEGER			NOT NULL,
	areaid					VARCHAR(200)	NOT NULL,
	x						INTEGER			NOT NULL,
	y						INTEGER			NOT NULL,
    optimised_geojson		Text,
	within					bit				NOT NULL
);


-- SQL statement 324: Add geometry column: bbox >>>
/*
 * SQL statement name: 	add_geometry_column2.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. geometry_cb_2014_us_500k
 *						2: column name; e.g. geom
 *						3: Column SRID; e.g. 4326 [NEVER USED IN SQL SERVER, set during WKT conversion]
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON [NEVER USED IN SQL SERVER]
 *                      5: Schema (rif_data. or "")
 *
 * Description:			Add *** geometry *** column to table
 * Note:				%% becomes % after substitution
 */
ALTER TABLE tile_intersects_usa_2014 ADD bbox geometry;


-- SQL statement 325: Add geometry column: geom >>>
/*
 * SQL statement name: 	add_geometry_column2.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: Table name; e.g. geometry_cb_2014_us_500k
 *						2: column name; e.g. geom
 *						3: Column SRID; e.g. 4326 [NEVER USED IN SQL SERVER, set during WKT conversion]
 *						4: Spatial geometry type: e.g. POINT, MULTIPOLYGON [NEVER USED IN SQL SERVER]
 *                      5: Schema (rif_data. or "")
 *
 * Description:			Add *** geometry *** column to table
 * Note:				%% becomes % after substitution
 */
ALTER TABLE tile_intersects_usa_2014 ADD geom geometry;


-- SQL statement 326: Comment tile intersects table >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_table.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. cb_2014_us_county_500k
 *						2: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 *
 * Description:			Comment table
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name]     = N'MS_Description'
		   AND [minor_id] = 0)
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Tile area id intersects',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Tile area id intersects',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014';


-- SQL statement 327: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'geolevel_id';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'ID for ordering (1=lowest resolution). Up to 99 supported.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'geolevel_id';


-- SQL statement 328: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'zoomlevel';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Zoom level: 0 to 11. Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at zoomlevel 11',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'zoomlevel'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Zoom level: 0 to 11. Number of tiles is 2**<zoom level> * 2**<zoom level>; i.e. 1, 2x2, 4x4 ... 2048x2048 at zoomlevel 11',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'zoomlevel';


-- SQL statement 329: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'areaid';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'areaid'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Area ID',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'areaid';


-- SQL statement 330: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'x';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'X tile number. From 0 to (2**<zoomlevel>)-1',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'x'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'X tile number. From 0 to (2**<zoomlevel>)-1',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'x';


-- SQL statement 331: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'y';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Y tile number. From 0 to (2**<zoomlevel>)-1',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'y'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Y tile number. From 0 to (2**<zoomlevel>)-1',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'y';


-- SQL statement 332: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'optimised_geojson';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Tile areaid intersect multipolygon in GeoJSON format, optimised for zoomlevel N.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'optimised_geojson'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Tile areaid intersect multipolygon in GeoJSON format, optimised for zoomlevel N.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'optimised_geojson';


-- SQL statement 333: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'within';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Defined as: ST_Within(bbox, geom). Used to exclude any tile bounding completely within the area.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'within'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Defined as: ST_Within(bbox, geom). Used to exclude any tile bounding completely within the area.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'within';


-- SQL statement 334: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'bbox';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Bounding box of tile as a polygon.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'bbox'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Bounding box of tile as a polygon.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'bbox';


-- SQL statement 335: Comment tile intersects table column >>>
DECLARE @CurrentUser sysname
DECLARE @columnName  sysname
DECLARE @tableName   sysname  /*
 * SQL statement name: 	comment_column.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: table; e.g. geolevels_cb_2014_us_county_500k
 *						2: column; e.g. geolevel_name
 *						3: comment. Usual rules for comment text in SQK - single
 *									quotes (') need to be double ('')
 *
 * 						SchemaName is set to either @CurrentUser (build) or 'rif_data' for rif40
 * Description:			Comment table column
 * Note:				%% becomes % after substitution
 */
SELECT @CurrentUser = user_name();
SELECT @tableName  = '@CurrentUser';
IF (@tableName = '@CurrentUser')
	SELECT @tableName = @CurrentUser + '.tile_intersects_usa_2014'
ELSE
	SELECT @tableName = '@CurrentUser.tile_intersects_usa_2014';
SELECT @columnName  = 'geom';
IF EXISTS (
        SELECT class_desc
          FROM SYS.EXTENDED_PROPERTIES
		 WHERE [major_id] = OBJECT_ID(@tableName)
           AND [name] = N'MS_Description'
		   AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = @columnName AND [object_id] = OBJECT_ID(@tableName)))
    EXECUTE sp_updateextendedproperty
		@name = N'MS_Description',
		@value = N'Geometry of area.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'geom'
ELSE
	EXECUTE sp_addextendedproperty
		@name = N'MS_Description',
		@value = N'Geometry of area.',
		@level0type = N'Schema', @level0name = @CurrentUser,
		@level1type = N'Table', @level1name = 'tile_intersects_usa_2014',
		@level2type = N'Column', @level2name = 'geom';


-- SQL statement 336: INSERT into tile intersects table >>>
/*
 * SQL statement name: 	tile_intersects_insert.sql
 * Type:				MS SQL Server SQL
 * Parameters:
 *						1: Tile intersects table name; e.g. tile_intersects_cb_2014_us_500k
 *						2: Tile limits table name; e.g. tile_limits_cb_2014_us_500k
 *						3: Geometry table name; e.g. geometry_cb_2014_us_500k
 *
 * Description:			Insert into tile intersects table
 * Note:				% becomes % after substitution
 */
WITH a AS (
	SELECT zoomlevel, x_mintile, x_maxtile, y_mintile, y_maxtile
	  FROM tile_limits_usa_2014
	 WHERE zoomlevel = 0
), x AS (
	SELECT zoomlevel, z.IntValue AS x_series
	  FROM a CROSS APPLY peter.generate_series(x_mintile, x_maxtile, 1) z
), y AS (
	SELECT zoomlevel, z.IntValue AS y_series
	  FROM a CROSS APPLY peter.generate_series(y_mintile, y_maxtile, 1) z
), b AS (
	SELECT x.zoomlevel,
	       x.x_series AS x,
	       y.y_series AS y,
	       peter.tileMaker_tile2longitude(x.x_series, x.zoomlevel) AS xmin,
		   peter.tileMaker_tile2latitude(y.y_series, x.zoomlevel) AS ymin,
		   peter.tileMaker_tile2longitude(x.x_series+1, x.zoomlevel) AS xmax,
		   peter.tileMaker_tile2latitude(y.y_series+1, x.zoomlevel) AS ymax
      FROM x, y
	 WHERE x.zoomlevel = y.zoomlevel
), c AS (
	SELECT b.zoomlevel, b.x, b.y,
		   peter.tileMaker_STMakeEnvelope(b.xmin, b.ymin, b.xmax, b.ymax, 4326) AS bbox,
		   c.geolevel_id,
		   c.areaid,
		   c.geom
	  FROM b, geometry_usa_2014 c
	 WHERE c.zoomlevel = 6
	   AND peter.tileMaker_STMakeEnvelope(b.xmin, b.ymin, b.xmax, b.ymax, 4326).STIntersects(c.geom) = 1 /* intersects */
), tile_intersects_temp AS (
	SELECT c.geolevel_id,
		   c.zoomlevel,
		   c.areaid,
		   c.x,
		   c.y,
		   c.bbox,
		   c.geom,
		   NULL AS optimised_geojson,
		   c.bbox.STWithin(c.geom) AS within /* Used to exclude any tile boundary completely within the area, i.e. there are no bounaries in the tile */
	  FROM c
)
INSERT INTO tile_intersects_usa_2014 (
	geolevel_id,
	zoomlevel,
	areaid,
	x,
	y,
	bbox,
	geom,
    optimised_geojson,
	within
)
SELECT geolevel_id,
	   zoomlevel,
	   areaid,
	   x,
	   y,
       bbox,
	   geom,
       optimised_geojson,
	   within
  FROM tile_intersects_temp
 ORDER BY geolevel_id, zoomlevel, x, y;


(3290 rows affected)

-- SQL statement 337: Add non clustered primary key >>>
ALTER TABLE tile_intersects_usa_2014 ADD PRIMARY KEY NONCLUSTERED (geolevel_id, zoomlevel, areaid, x, y) ;


-- SQL statement 338: Analyze table >>>
UPDATE STATISTICS tile_intersects_usa_2014;


-- SQL statement 339: SELECT from tile intersects table >>>
/*
 * SQL statement name: 	tile_intersects_select.sql
 * Type:				MS SQL Server SQL
 * Parameters:
 *						1: Tile intersects table name; e.g. tile_intersects_cb_2014_us_500k
 *
 * Description:			Select from tile intersects table

geolevel_id zoomlevel   areaid      x           y           within       bbox
----------- ----------- ----------- ----------- ----------- ----------- ---------------------------------------------------------
          1           0 US          0           0                     0 POLYGON ((-180 85.0511, -180 -85.0511, 180 -85.0511, 180 85.0511, -180 85.0511))


(1 rows affected)

 * Note:				% becomes % after substitution
 */
SELECT geolevel_id,
	   zoomlevel,
	   areaid,
	   x,
	   y,
	   within,
	   bbox.STAsText() AS bbox
  FROM tile_intersects_usa_2014
 WHERE zoomlevel = 0 AND geolevel_id = 1;

geolevel_id zoomlevel   areaid                                                                                                                                                                                                   x           y           within bbox
----------- ----------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------- ----------- ------ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
          1           0 US                                                                                                                                                                                                                 0           0      0 POLYGON ((-180 85.0511, -180 -85.0511, 180 -85.0511, 180 85.0511, -180 85.0511))

(1 rows affected)

-- SQL statement 340: INSERT into tile intersects table (MSSQLServer tile manufacture) >>>
/*
 * SQL statement name: 	tile_intersects_insert2.sql
 * Type:				MS SQL Server SQL
 * Parameters:
 *						1: Geometry table name; e.g. geometry_cb_2014_us_500k
 *						2: Geolevels table name; e.g. geolevels_cb_2014_us_500k
 *						3: Tile intersects table name; e.g. tile_intersects_cb_2014_us_500k
 *						4: Tile limits table name; e.g. tile_limits_cb_2014_us_500k
 *
 * Description:			Insert into tile intersects table
 * Note:				% becomes % after substitution
 *
 * To performance trace add to script:
 *
 * SET STATISTICS PROFILE ON
 * SET STATISTICS TIME ON
 *
 * You may need to change #temp to temp (i.e. make it a real table to profile it)
 */
--
-- For testing
--
--DECLARE @start_zoomlevel INTEGER=6;
--DECLARE @start_geolevel_id INTEGER=3;
DECLARE @start_zoomlevel INTEGER=1;
DECLARE @start_geolevel_id INTEGER=1;

DECLARE c1_maxgeolevel_id 	CURSOR FOR
		SELECT MAX(geolevel_id) AS max_geolevel_id,
	           MAX(zoomlevel) AS max_zoomlevel
	      FROM geometry_usa_2014;
DECLARE c2_areaid_count 	CURSOR FOR
		SELECT areaid_count
		  FROM geolevels_usa_2014
		 WHERE geolevel_id = 1;
--
DECLARE @max_geolevel_id INTEGER;
DECLARE @max_zoomlevel INTEGER;
DECLARE @areaid_count INTEGER;
DECLARE @l_use_zoomlevel INTEGER;
DECLARE @geolevel_id INTEGER;
DECLARE @zoomlevel INTEGER;
--
DECLARE @i INTEGER;
DECLARE @j INTEGER;
--
DECLARE @rowc INTEGER;
DECLARE @rowc2 INTEGER;
--
DECLARE @pstart DATETIME;
DECLARE @sstart DATETIME;
DECLARE @lstart DATETIME;
--
DECLARE @etime TIME;
--
DECLARE @isecs   NUMERIC;
DECLARE @cisecs  VARCHAR(40);
--
DECLARE @cesecs  VARCHAR(40);
DECLARE @esecs   NUMERIC;
DECLARE @cesecs1 VARCHAR(40);
DECLARE @cesecs2 VARCHAR(40);
DECLARE @cesecs3 VARCHAR(40);
DECLARE @cesecs4 VARCHAR(40);
DECLARE @cesecs5 VARCHAR(40);
--
BEGIN
	OPEN c1_maxgeolevel_id;
	FETCH c1_maxgeolevel_id INTO @max_geolevel_id, @max_zoomlevel;
	CLOSE c1_maxgeolevel_id;
	DEALLOCATE c1_maxgeolevel_id;
--
	OPEN c2_areaid_count;
	FETCH c2_areaid_count INTO @areaid_count;
	CLOSE c2_areaid_count;
	DEALLOCATE c2_areaid_count;
--
	IF @areaid_count = 1 	/* 0/0/0 tile only;  */
		SET @start_geolevel_id=2;
	ELSE
		SET @start_geolevel_id=1;
--
	SET @i=@start_geolevel_id;
	DELETE FROM tile_intersects_usa_2014
	 WHERE zoomlevel >= @start_zoomlevel;
--
-- Override for test purposes
--
--	SET @max_zoomlevel=7;
--
	SET @pstart = GETDATE();
--
	WHILE @i <= @max_geolevel_id /* FOR i IN start_geolevel_id .. max_geolevel_id LOOP */
	BEGIN
		SET @geolevel_id=@i;
		SET @j=@start_zoomlevel;
		WHILE @j <= @max_zoomlevel /* FOR j IN 1 .. max_zoomlevel LOOP */
		BEGIN
			SET @sstart = GETDATE();
			SET @lstart = GETDATE();
			SET @zoomlevel=@j;
--
			SET @l_use_zoomlevel=@zoomlevel;
			IF @zoomlevel<6
				SET @l_use_zoomlevel=6;
--
-- Intersector2: tile intersects table INSERT function. Zoomlevels <6 use zoomlevel 6 data
--
-- Step 1: Calculate bounding box, parent X/Y min
--		   This is separate to prevent SQL Server unnesting the cross join because it thinks it is very inefficent
--		   This could probably be improved with manual statistics for the function, but there is no method for this in SQL Server
--
			WITH a	AS (
				SELECT b.zoomlevel AS zoomlevel, b.x_mintile, b.x_maxtile, b.y_mintile, b.y_maxtile
				  FROM tile_limits_usa_2014 b
				 WHERE @zoomlevel = b.zoomlevel
			), x AS (
				SELECT zoomlevel, z.IntValue AS x_series
				  FROM a CROSS APPLY peter.generate_series(x_mintile, x_maxtile, 1) z
			), y AS (
				SELECT zoomlevel, z.IntValue AS y_series
				  FROM a CROSS APPLY peter.generate_series(y_mintile, y_maxtile, 1) z
			), b AS (
				SELECT x.zoomlevel,
					   x.x_series AS x,
					   y.y_series AS y,
					   peter.tileMaker_tile2longitude(x.x_series, x.zoomlevel) AS xmin,
					   peter.tileMaker_tile2latitude(y.y_series, x.zoomlevel) AS ymin,
					   peter.tileMaker_tile2longitude(x.x_series+1, x.zoomlevel) AS xmax,
					   peter.tileMaker_tile2latitude(y.y_series+1, x.zoomlevel) AS ymax
				  FROM x, y /* Explicit cross join */
				 WHERE x.zoomlevel = y.zoomlevel
			) /* Calculate bounding box, parent X/Y min */
			SELECT b.zoomlevel,
				   b.x,
				   b.y,
				   peter.tileMaker_STMakeEnvelope(b.xmin, b.ymin, b.xmax, b.ymax, 4326) AS bbox,
				   peter.tileMaker_latitude2tile(b.ymin, b.zoomlevel-1) AS parent_ymin,
				   peter.tileMaker_longitude2tile(b.xmin, b.zoomlevel-1) AS parent_xmin
			  INTO #temp2
			  FROM b
			 ORDER BY b.zoomlevel, b.x, b.y;
--
			SET @etime = CAST(GETDATE() - @lstart AS TIME);
			SET @esecs = (DATEPART(MILLISECOND, @etime));
			SET @esecs = @esecs/10;
			SET @cesecs1 = CAST((DATEPART(HOUR, @etime) * 3600) + (DATEPART(MINUTE, @etime) * 60) + (DATEPART(SECOND, @etime)) AS VARCHAR(40)) +
					'.' + CAST(ROUND(@esecs, 1) AS VARCHAR(40));
			SET @lstart = GETDATE();
--
-- Step 2: Join to parent tile from previous geolevel_id; i.e. exclude if not present, intersect by bounding box (this in combination
--         removes most tiles not containing data efficiently). This was the cause of most performance problems when SQL Server decided to
--         change this order. The COUNT(*) always returns 1; it is to prevent SQL Server unesting the query!
-- 		   This may cause problems in future if SQL Server becomes intelligent enough to spot this; although hopefully it will by then
-- 	       spot the STIntersect() is an expensive operation even with indexes
--
			WITH d AS ( /* Get parent tiles */
				SELECT p.x, p.y, p.areaid, COUNT(p.x) AS total
				  FROM tile_intersects_usa_2014 p /* Parent */
				 WHERE p.zoomlevel    = @zoomlevel -1 	/* previous geolevel_id: c.zoomlevel -1 */
				   AND p.geolevel_id  = @geolevel_id
				 GROUP BY p.x, p.y, p.areaid
			), e AS (
				SELECT c.zoomlevel, c.x, c.y, d.areaid, c.bbox
				  FROM #temp2 c, d
				 WHERE c.parent_xmin = d.x  			/* Join to parent tile from previous geolevel_id; i.e. exclude if not present */
				   AND c.parent_ymin = d.y
			)
			SELECT e.zoomlevel, e.x, e.y, e.areaid, e.bbox, e2.geom
			  INTO #temp
			  FROM e, geometry_usa_2014 e2
			 WHERE e2.zoomlevel    = @l_use_zoomlevel
			   AND e2.geolevel_id  = @geolevel_id
			   AND e2.areaid       = e.areaid
			   AND e.bbox.STIntersects(e2.bbox) = 1		/* Intersect by bounding box */
			 ORDER BY e.zoomlevel, e.x, e.y, e.areaid;
			DROP TABLE #temp2;
--
			SET @etime = CAST(GETDATE() - @lstart AS TIME);
			SET @esecs = (DATEPART(MILLISECOND, @etime));
			SET @esecs = @esecs/10;
			SET @cesecs5 = CAST((DATEPART(HOUR, @etime) * 3600) + (DATEPART(MINUTE, @etime) * 60) + (DATEPART(SECOND, @etime)) AS VARCHAR(40)) +
					'.' + CAST(ROUND(@esecs, 1) AS VARCHAR(40));
			SET @lstart = GETDATE();
--
-- Do NOT index #temp; it i slower and gives the wrong answer
--
/*
			ALTER TABLE #temp ALTER COLUMN x INTEGER NOT NULL;
			ALTER TABLE #temp ALTER COLUMN y INTEGER NOT NULL;
			ALTER TABLE #temp ALTER COLUMN areaid INTEGER NOT NULL;
			ALTER TABLE #temp ADD PRIMARY KEY (x, y, areaid);
			CREATE SPATIAL INDEX #temp_gix ON #temp (geom)
				WITH ( BOUNDING_BOX = (xmin=-179.148909, ymin=-14.548699000000001, xmax=179.77847, ymax=71.36516200000001));
			CREATE SPATIAL INDEX #temp_gix2 ON #temp (bbox)
				WITH ( BOUNDING_BOX = (xmin=-179.148909, ymin=-14.548699000000001, xmax=179.77847, ymax=71.36516200000001));
--
			SET @etime = CAST(GETDATE() - @lstart AS TIME);
			SET @esecs = (DATEPART(MILLISECOND, @etime));
			SET @esecs = @esecs/10;
			SET @cesecs6 = CAST((DATEPART(HOUR, @etime) * 3600) + (DATEPART(MINUTE, @etime) * 60) + (DATEPART(SECOND, @etime)) AS VARCHAR(40)) +
					'.' + CAST(ROUND(@esecs, 1) AS VARCHAR(40));
			SET @lstart = GETDATE();
			*/
--
-- Step 3: intersects tile bounding box with geometry, exclude any tile bounded completely within the area
--
			WITH f AS (
				SELECT @geolevel_id AS geolevel_id, e.zoomlevel, e.x, e.y, e.bbox, e.areaid, e.geom
				  FROM #temp e
				 WHERE e.bbox.STIntersects(e.geom) = 1 /* intersects tile bounding box with geometry */
			)
			INSERT INTO tile_intersects_usa_2014(geolevel_id, zoomlevel, areaid, x, y, bbox, geom, optimised_geojson, within)
			SELECT f.geolevel_id, f.zoomlevel, f.areaid, f.x, f.y, f.bbox, f.geom,
				   NULL AS optimised_geojson,
				   1 AS within
			  FROM f
			 WHERE NOT f.bbox.STWithin(f.geom) = 1 /* Exclude any tile bounded completely within the area */
			 ORDER BY f.geolevel_id, f.zoomlevel, f.areaid, f.x, f.y;
--
			SET @rowc = @@ROWCOUNT;
			SET @etime = CAST(GETDATE() - @lstart AS TIME);
			SET @esecs = (DATEPART(MILLISECOND, @etime));
			SET @esecs = @esecs/10;
			SET @cesecs2 = CAST((DATEPART(HOUR, @etime) * 3600) + (DATEPART(MINUTE, @etime) * 60) + (DATEPART(SECOND, @etime)) AS VARCHAR(40)) +
					'.' + CAST(ROUND(@esecs, 1) AS VARCHAR(40));
--
			DROP TABLE #temp;
--
-- Run 2
--
			SET @lstart = GETDATE();
--
-- Intersector2: tile intersects table INSERT function. Zoomlevels <6 use zoomlevel 6 data
--				Insert tile area id intersections missing where not in the previous layer;
--				this is usually due to it being simplified out of existance.
--
			WITH a AS (
				SELECT DISTINCT geolevel_id, areaid
				  FROM geometry_usa_2014
				 WHERE geolevel_id = @geolevel_id
				   AND zoomlevel   = @zoomlevel
				EXCEPT
				SELECT DISTINCT geolevel_id, areaid
				  FROM tile_intersects_usa_2014 a
				 WHERE geolevel_id = @geolevel_id
				   AND zoomlevel   = @zoomlevel
			), b AS (
				SELECT a.geolevel_id, a.areaid, b.geom.STEnvelope() AS bbox, b.geom
				  FROM a, geometry_usa_2014 b
				 WHERE a.geolevel_id = @geolevel_id
				   AND zoomlevel     = @zoomlevel
				   AND a.areaid      = b.areaid
				   AND NOT b.geom.STIsEmpty() = 1
			), c1 AS (
				SELECT @zoomlevel AS zoomlevel,
					   b.geolevel_id,
					   b.areaid,
					   peter.tileMaker_latitude2tile(geometry::EnvelopeAggregate(bbox).STPointN(1).STY  /* Ymin */, @zoomlevel) AS y_mintile,
					   peter.tileMaker_longitude2tile(geometry::EnvelopeAggregate(bbox).STPointN(1).STX /* Xmin */, @zoomlevel) AS x_mintile,
					   peter.tileMaker_latitude2tile(geometry::EnvelopeAggregate(bbox).STPointN(3).STY  /* Ymax */, @zoomlevel) AS y_maxtile,
					   peter.tileMaker_longitude2tile(geometry::EnvelopeAggregate(bbox).STPointN(3).STX /* Xmax */, @zoomlevel) AS x_maxtile
				   FROM b
				  GROUP BY b.geolevel_id,
					   b.areaid
			), c AS (
				SELECT c1.zoomlevel,
					   c1.geolevel_id,
					   c1.areaid,
					   c1.x_mintile,
					   c1.y_mintile,
					   c1.x_maxtile,
					   c1.y_maxtile,
					   b.geom
				  FROM c1, b
				 WHERE c1.areaid = b.areaid
			), x AS (
				SELECT c.zoomlevel,
					   c.geolevel_id,
					   c.areaid,
					   z.IntValue AS x_series
				  FROM c CROSS APPLY peter.generate_series(x_mintile, x_maxtile, 1) z
			), y AS (
				SELECT c.zoomlevel,
					   c.geolevel_id,
					   c.areaid,
					   z.IntValue AS y_series
				  FROM c CROSS APPLY peter.generate_series(y_mintile, y_maxtile, 1) z
			), d AS (
				SELECT x.zoomlevel,
					   x.geolevel_id,
					   x.areaid,
					   x.x_series AS x,
					   y.y_series AS y,
					   peter.tileMaker_tile2longitude(x.x_series, x.zoomlevel) AS xmin,
					   peter.tileMaker_tile2latitude(y.y_series, x.zoomlevel) AS ymin,
					   peter.tileMaker_tile2longitude(x.x_series+1, x.zoomlevel) AS xmax,
					   peter.tileMaker_tile2latitude(y.y_series+1, x.zoomlevel) AS ymax
				  FROM x, y
				 WHERE x.zoomlevel   = y.zoomlevel
				   AND x.geolevel_id = y.geolevel_id
				   AND x.areaid      = y.areaid
			), e AS (
				SELECT d.zoomlevel,
					   d.geolevel_id,
					   d.areaid,
					   d.x,
					   d.y,
					   peter.tileMaker_STMakeEnvelope(d.xmin, d.ymin, d.xmax, d.ymax, 4326) AS bbox
				  FROM d
			), f1 AS (
				SELECT DISTINCT e.zoomlevel,
					   e.geolevel_id,
					   e.areaid,
					   e.x,
					   e.y
				  FROM e
				 WHERE NOT EXISTS (SELECT c2.areaid
									 FROM tile_intersects_usa_2014 c2
									WHERE c2.geolevel_id = @geolevel_id
									  AND c2.zoomlevel   = @zoomlevel
									  AND c2.x           = e.x
									  AND c2.y           = e.y
									  AND c2.areaid      = e.areaid)
			), f AS (
				SELECT f1.zoomlevel,
					   f1.geolevel_id,
					   f1.areaid,
					   f1.x,
					   f1.y,
					   e.bbox
				  FROM f1, e
				 WHERE e.areaid      = f1.areaid
				   AND e.x           = f1.x
				   AND e.y           = f1.y
				   AND e.zoomlevel   = f1.zoomlevel
				   AND e.geolevel_id = f1.geolevel_id
			), g AS (
					SELECT f.zoomlevel, f.geolevel_id, f.x, f.y, f.bbox, e2.areaid, e2.geom
					  FROM f, geometry_usa_2014 e2
					 WHERE e2.zoomlevel    = @l_use_zoomlevel
					   AND e2.geolevel_id  = @geolevel_id
					   AND e2.areaid       = f.areaid
				       AND f.bbox.STIntersects(e2.bbox) = 1	/* Intersect by bounding box */
					   AND f.bbox.STIntersects(e2.geom) = 1 /* intersects: (e.bbox && e.geom) is slower as it generates many more tiles */
			)
			INSERT INTO tile_intersects_usa_2014(geolevel_id, zoomlevel, areaid, x, y, bbox, geom, optimised_geojson, within)
			SELECT geolevel_id, zoomlevel, areaid, x, y, bbox, geom,
				   NULL AS optimised_geojson,
				   g.bbox.STWithin(g.geom) AS within
			  FROM g
			 ORDER BY geolevel_id, zoomlevel, areaid, x, y;
--
			SET @rowc2 = @@ROWCOUNT;
--
			SET @etime = CAST(GETDATE() - @lstart AS TIME);
			SET @esecs = (DATEPART(MILLISECOND, @etime));
			SET @esecs = @esecs/10;
			SET @cesecs3 = CAST((DATEPART(HOUR, @etime) * 3600) + (DATEPART(MINUTE, @etime) * 60) + (DATEPART(SECOND, @etime)) AS VARCHAR(40)) +
					'.' + CAST(ROUND(@esecs, 1) AS VARCHAR(40));
			SET @lstart = GETDATE();
--
-- Rebuild tile intersects index
--
			ALTER INDEX ALL ON tile_intersects_usa_2014 REORGANIZE;
--
			SET @etime = CAST(GETDATE() - @lstart AS TIME);
			SET @esecs = (DATEPART(MILLISECOND, @etime));
			SET @esecs = @esecs/10;
			SET @cesecs4 = CAST((DATEPART(HOUR, @etime) * 3600) + (DATEPART(MINUTE, @etime) * 60) + (DATEPART(SECOND, @etime)) AS VARCHAR(40)) +
					'.' + CAST(ROUND(@esecs, 1) AS VARCHAR(40));
--
-- Calculate overall time since start
--
			SET @etime = CAST(GETDATE() - @pstart AS TIME);
			SET @esecs = (DATEPART(MILLISECOND, @etime));
			SET @esecs = @esecs/10;
			SET @cesecs = CAST((DATEPART(HOUR, @etime) * 3600) + (DATEPART(MINUTE, @etime) * 60) + (DATEPART(SECOND, @etime)) AS VARCHAR(40)) +
					'.' + CAST(ROUND(@esecs, 1) AS VARCHAR(40));
--
-- Calculate intersects/s for this geolevel/zoomlevel combination
--
			SET @etime = CAST(GETDATE() - @sstart AS TIME); -- For all queries in fop loop
			IF (DATEPART(SECOND, @etime) > 0)
				SET @isecs=@rowc/((DATEPART(HOUR, @etime) * 3600) + (DATEPART(MINUTE, @etime) * 60) + (DATEPART(SECOND, @etime)));
			ELSE
				SET @isecs=0;
			SET @cisecs=CAST(ROUND(@isecs, 1) AS VARCHAR(40))
--
-- Processed 57+0 total areaid intersects, 3 tiles for geolevel id 2/3 zoomlevel: 1/11 in 0.7+0.0s+0.3s, 1.9s total; 92.1 intesects/s
--
			RAISERROR('Processed %d+%d for geolevel id: %d/%d; zoomlevel: %d/%d; in #temp2: %s, #temp: %s, insert: %s, insert2: %s, re-index: %s, %s total; %s intesects/s)', 10, 1,
				@rowc, @rowc2, @geolevel_id, @max_geolevel_id, @zoomlevel, @max_zoomlevel,
				@cesecs1, -- #temp2 create
				@cesecs5, -- #temp create
				@cesecs2, -- INSERT into tile intersects table
				@cesecs3, -- 2nd INSERT into tile intersects table (Insert tile area id intersections missing where not in the previous layer)
				@cesecs4, -- Re-index tile intersects table
				@cesecs, -- Overall running total
				@cisecs  -- Intersects/sec
				) WITH NOWAIT;
			SET @j+=1;
		END;
		SET @i+=1;
	END;
--
END;


(0 rows affected)

(4 rows affected)

(57 rows affected)

(57 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 57+0 for geolevel id: 2/3; zoomlevel: 1/9; in #temp2: 0.0, #temp: 0.38, insert: 0.27, insert2: 0.1, re-index: 0.2, 0.68 total; 0 intesects/s)

(12 rows affected)

(72 rows affected)

(67 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 67+0 for geolevel id: 2/3; zoomlevel: 2/9; in #temp2: 0.0, #temp: 0.6, insert: 0.81, insert2: 0.2, re-index: 0.0, 1.57 total; 0 intesects/s)

(32 rows affected)

(83 rows affected)

(81 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 81+0 for geolevel id: 2/3; zoomlevel: 3/9; in #temp2: 0.1, #temp: 0.5, insert: 0.63, insert2: 0.2, re-index: 0.0, 2.29 total; 0 intesects/s)

(96 rows affected)

(101 rows affected)

(95 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 95+0 for geolevel id: 2/3; zoomlevel: 4/9; in #temp2: 0.2, #temp: 0.6, insert: 1.44, insert2: 0.2, re-index: 0.0, 3.82 total; 95 intesects/s)

(384 rows affected)

(158 rows affected)

(142 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 142+0 for geolevel id: 2/3; zoomlevel: 5/9; in #temp2: 0.6, #temp: 0.8, insert: 2.47, insert2: 0.2, re-index: 0.0, 6.45 total; 71 intesects/s)

(1408 rows affected)

(286 rows affected)

(242 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 242+0 for geolevel id: 2/3; zoomlevel: 6/9; in #temp2: 0.21, #temp: 0.14, insert: 6.25, insert2: 1.55, re-index: 0.0, 14.60 total; 30 intesects/s)

(5504 rows affected)

(625 rows affected)

(487 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 487+0 for geolevel id: 2/3; zoomlevel: 7/9; in #temp2: 0.84, #temp: 0.42, insert: 18.91, insert2: 2.29, re-index: 0.1, 37.8 total; 22 intesects/s)

(21760 rows affected)

(1484 rows affected)

(1020 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 1020+0 for geolevel id: 2/3; zoomlevel: 8/9; in #temp2: 3.22, #temp: 2.43, insert: 50.79, insert2: 1.75, re-index: 0.3, 95.30 total; 17 intesects/s)

(86359 rows affected)

(3491 rows affected)

(2248 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 2248+0 for geolevel id: 2/3; zoomlevel: 9/9; in #temp2: 12.83, #temp: 18.21, insert: 153.11, insert2: 2.68, re-index: 0.7, 282.19 total; 12 intesects/s)

(4 rows affected)

(3234 rows affected)

(3234 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 3234+0 for geolevel id: 3/3; zoomlevel: 1/9; in #temp2: 0.0, #temp: 0.55, insert: 0.73, insert2: 0.75, re-index: 0.7, 284.30 total; 1617 intesects/s)

(12 rows affected)

(3294 rows affected)

(3292 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 3292+0 for geolevel id: 3/3; zoomlevel: 2/9; in #temp2: 0.0, #temp: 0.55, insert: 0.76, insert2: 0.69, re-index: 0.7, 286.38 total; 1646 intesects/s)

(32 rows affected)

(3393 rows affected)

(3391 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 3391+0 for geolevel id: 3/3; zoomlevel: 3/9; in #temp2: 0.1, #temp: 0.58, insert: 1.19, insert2: 0.59, re-index: 0.8, 288.82 total; 1695 intesects/s)

(96 rows affected)

(3448 rows affected)

(3441 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 3441+0 for geolevel id: 3/3; zoomlevel: 4/9; in #temp2: 0.2, #temp: 0.60, insert: 0.86, insert2: 0.4, re-index: 0.8, 290.41 total; 3441 intesects/s)

(384 rows affected)

(3668 rows affected)

(3659 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 3659+0 for geolevel id: 3/3; zoomlevel: 5/9; in #temp2: 0.6, #temp: 0.61, insert: 0.95, insert2: 0.47, re-index: 0.7, 292.57 total; 1829 intesects/s)

(1408 rows affected)

(4104 rows affected)

(4065 rows affected)

(4 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 4065+4 for geolevel id: 3/3; zoomlevel: 6/9; in #temp2: 0.22, #temp: 0.74, insert: 1.21, insert2: 3.6, re-index: 0.7, 297.88 total; 813 intesects/s)

(5504 rows affected)

(5116 rows affected)

(4990 rows affected)

(0 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 4990+0 for geolevel id: 3/3; zoomlevel: 7/9; in #temp2: 0.80, #temp: 0.77, insert: 4.21, insert2: 1.54, re-index: 0.8, 305.28 total; 712 intesects/s)

(21760 rows affected)

(7561 rows affected)

(7129 rows affected)

(4 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 7129+4 for geolevel id: 3/3; zoomlevel: 8/9; in #temp2: 3.18, #temp: 0.94, insert: 7.80, insert2: 3.59, re-index: 0.8, 320.87 total; 475 intesects/s)

(86359 rows affected)

(13679 rows affected)

(12273 rows affected)

(5 rows affected)
Msg 50000, Level 0, State 1, Server PH-LAPTOP\SQLEXPRESS, Line 394
Processed 12273+5 for geolevel id: 3/3; zoomlevel: 9/9; in #temp2: 12.61, #temp: 1.88, insert: 16.75, insert2: 4.45, re-index: 0.9, 356.66 total; 350 intesects/s)

-- SQL statement 341: Special index on tile intersects table for MS SQL tuning >>>
/*
 * SQL statement name: 	tile_intersects_usa_2014_tlidx.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: tile intersects table; e.g. tile_intersects_usa_2014
 *
 * Description:			Special index on tile intersects table for MS SQL tuning.
 *						SQL server is very inefficent otherwise
 * Note:				% becomes % after substitution
 */
CREATE NONCLUSTERED INDEX tile_intersects_usa_2014_tlidx
ON tile_intersects_usa_2014 ([geolevel_id],[zoomlevel],[x],[y])
INCLUDE ([areaid],[geom]);


-- SQL statement 342: Tile intersects table % savings >>>
/*
 * SQL statement name: 	tile_intersects_select2.sql
 * Type:				MS SQL Server SQL
 * Parameters:
 *						1: Tile intersects table name; e.g. tile_intersects_cb_2014_us_500k
 *
 * Description:			Select from tile intersects table

geolevel_id zoomlevel   areas       xmin        ymin        xmax        ymax        possible_tiles tiles       pct_saving
----------- ----------- ----------- ----------- ----------- ----------- ----------- -------------- ----------- ----------
          1           0           1           0           0           0           0              1           1         .0
          2           0          56           0           0           0           0              1           1         .0
          2           1          56           0           0           1           1              4           3       25.0
          2           2          56           0           0           3           2             12           5       58.3
          2           3          56           0           1           7           4             32          10       68.8
          2           4          56           0           3          15           8             96          22       77.1
          2           5          56           0           6          31          17            384          48       87.5
          2           6          56           0          13          63          34           1408         111       92.1
          2           7          56           0          27         127          69           5504         281       94.9
          2           8          56           0          54         255         135          20992         665       96.8
          3           0        3233           0           0           0           0              1           1         .0
          3           1        3233           0           0           1           1              4           3       25.0
          3           2        3233           0           0           3           2             12           5       58.3
          3           3        3233           0           1           7           4             32          10       68.8
          3           4        3233           0           3          15           8             96          22       77.1
          3           5        3233           0           6          31          17            384          49       87.2
          3           6        3233           0          13          63          34           1408         119       91.6
          3           7        3233           0          27         127          69           5504         333       94.0
          3           8        3233           0          54         255         138          21760         992       95.4

(19 rows affected)

 * Note:				% becomes % after substitution
 */
SELECT geolevel_id, zoomlevel,
       COUNT(DISTINCT(areaid)) AS areas,
       MIN(x) AS xmin, MIN(y) AS ymin,
       MAX(x) AS xmax, MAX(y) AS ymax,
	   (MAX(x)-MIN(x)+1)*(MAX(y)-MIN(y)+1) AS possible_tiles,
       COUNT(DISTINCT(CAST(x AS VARCHAR) + CAST(y AS VARCHAR))) AS tiles,
	   CAST(ROUND((CAST( (((MAX(x)-MIN(x)+1)*(MAX(y)-MIN(y)+1)) /* possible_tiles */ - COUNT(DISTINCT(CAST(x AS VARCHAR) + CAST(y AS VARCHAR)))) AS NUMERIC)/
			((MAX(x)-MIN(x)+1)*(MAX(y)-MIN(y)+1)))*100, 2) AS DECIMAL(4,1)) AS pct_saving
  FROM tile_intersects_usa_2014
 GROUP BY geolevel_id, zoomlevel
 ORDER BY 1, 2;

geolevel_id zoomlevel   areas       xmin        ymin        xmax        ymax        possible_tiles tiles       pct_saving
----------- ----------- ----------- ----------- ----------- ----------- ----------- -------------- ----------- ----------
          1           0           1           0           0           0           0              1           1         .0
          2           0          56           0           0           0           0              1           1         .0
          2           1          56           0           0           1           1              4           3       25.0
          2           2          56           0           0           3           2             12           5       58.3
          2           3          56           0           1           7           4             32          10       68.8
          2           4          56           0           3          15           8             96          22       77.1
          2           5          56           0           6          31          17            384          47       87.8
          2           6          56           0          13          63          34           1408         111       92.1
          2           7          56           0          27         127          69           5504         281       94.9
          2           8          56           0          54         255         135          20992         665       96.8
          2           9          56           1         108         511         271          83804        1568       98.1
          3           0        3233           0           0           0           0              1           1         .0
          3           1        3233           0           0           1           1              4           3       25.0
          3           2        3233           0           0           3           2             12           5       58.3
          3           3        3233           0           1           7           4             32          10       68.8
          3           4        3233           0           3          15           8             96          22       77.1
          3           5        3233           0           6          31          17            384          49       87.2
          3           6        3233           0          13          63          34           1408         119       91.6
          3           7        3233           0          27         127          69           5504         333       94.0
          3           8        3233           0          54         255         138          21760         992       95.4
          3           9        3233           1         108         511         276          86359        3137       96.4

(21 rows affected)

-- SQL statement 343: Commit transaction >>>
COMMIT;


--
-- Analyze tables
--

-- SQL statement 345: Describe table cb_2014_us_county_500k >>>
-- EXEC sp_help cb_2014_us_county_500k;


-- SQL statement 346: Analyze table cb_2014_us_county_500k >>>
UPDATE STATISTICS cb_2014_us_county_500k;


-- SQL statement 347: Describe table lookup_cb_2014_us_nation_5m >>>
-- EXEC sp_help lookup_cb_2014_us_nation_5m;


-- SQL statement 348: Analyze table lookup_cb_2014_us_nation_5m >>>
UPDATE STATISTICS lookup_cb_2014_us_nation_5m;


-- SQL statement 349: Describe table cb_2014_us_nation_5m >>>
-- EXEC sp_help cb_2014_us_nation_5m;


-- SQL statement 350: Analyze table cb_2014_us_nation_5m >>>
UPDATE STATISTICS cb_2014_us_nation_5m;


-- SQL statement 351: Describe table lookup_cb_2014_us_state_500k >>>
-- EXEC sp_help lookup_cb_2014_us_state_500k;


-- SQL statement 352: Analyze table lookup_cb_2014_us_state_500k >>>
UPDATE STATISTICS lookup_cb_2014_us_state_500k;


-- SQL statement 353: Describe table cb_2014_us_state_500k >>>
-- EXEC sp_help cb_2014_us_state_500k;


-- SQL statement 354: Analyze table cb_2014_us_state_500k >>>
UPDATE STATISTICS cb_2014_us_state_500k;


-- SQL statement 355: Describe table lookup_cb_2014_us_county_500k >>>
-- EXEC sp_help lookup_cb_2014_us_county_500k;


-- SQL statement 356: Analyze table lookup_cb_2014_us_county_500k >>>
UPDATE STATISTICS lookup_cb_2014_us_county_500k;


-- SQL statement 357: Describe table geolevels_usa_2014 >>>
-- EXEC sp_help geolevels_usa_2014;


-- SQL statement 358: Analyze table geolevels_usa_2014 >>>
UPDATE STATISTICS geolevels_usa_2014;


-- SQL statement 359: Describe table geography_usa_2014 >>>
-- EXEC sp_help geography_usa_2014;


-- SQL statement 360: Analyze table geography_usa_2014 >>>
UPDATE STATISTICS geography_usa_2014;


-- SQL statement 361: Describe table hierarchy_usa_2014 >>>
-- EXEC sp_help hierarchy_usa_2014;


-- SQL statement 362: Analyze table hierarchy_usa_2014 >>>
UPDATE STATISTICS hierarchy_usa_2014;


-- SQL statement 363: Describe table geometry_usa_2014 >>>
-- EXEC sp_help geometry_usa_2014;


-- SQL statement 364: Analyze table geometry_usa_2014 >>>
UPDATE STATISTICS geometry_usa_2014;


-- SQL statement 365: Describe table tile_intersects_usa_2014 >>>
-- EXEC sp_help tile_intersects_usa_2014;


-- SQL statement 366: Analyze table tile_intersects_usa_2014 >>>
UPDATE STATISTICS tile_intersects_usa_2014;


-- SQL statement 367: Describe table tile_limits_usa_2014 >>>
-- EXEC sp_help tile_limits_usa_2014;


-- SQL statement 368: Analyze table tile_limits_usa_2014 >>>
UPDATE STATISTICS tile_limits_usa_2014;


-- SQL statement 369: Describe table t_tiles_usa_2014 >>>
-- EXEC sp_help t_tiles_usa_2014;


-- SQL statement 370: Analyze table t_tiles_usa_2014 >>>
UPDATE STATISTICS t_tiles_usa_2014;


--
-- Check areas
--

-- SQL statement 372: Test Turf and DB areas agree to within 1% (Postgres)/5% (SQL server) >>>
DECLARE c1 CURSOR FOR
/*
 * SQL statement name: 	area_check.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Check Turf araa (area_km2) compared to SQL Server calculated area (area_km2_calc)
 *						Allow for 5% error
 *						Ignore small areas <= 15 km2
 * Note:				%% becomes % after substitution
 */
	WITH a AS (
		SELECT areaname,
			   CAST(area_km2 AS NUMERIC(15,2)) AS area_km2,
			   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(15,2)) AS area_km2_calc
		  FROM cb_2014_us_county_500k
	), b AS (
	SELECT a.areaname,
		   a.area_km2,
		   a.area_km2_calc,
		   CASE WHEN a.area_km2 > 0 THEN 100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2)
				WHEN a.area_km2 = a.area_km2_calc THEN 0
				ELSE NULL
		   END AS pct_km2_diff
	  FROM a
	), c AS (
		SELECT COUNT(areaname) AS total_areas
		  FROM a
	), d AS (
		SELECT b.areaname, b.area_km2, b.area_km2_calc, b.pct_km2_diff
		  FROM b, c
		 WHERE b.pct_km2_diff > 5 /* Allow for 5% error */
		   AND b.area_km2_calc > 15 /* Ignore small areas <= 15 km2 */
	), e AS (
		SELECT COUNT(areaname) AS total_areas_in_error
		  FROM d
	)
	SELECT d.areaname, d.area_km2, d.area_km2_calc, d.pct_km2_diff, c.total_areas AS total_areas, e.total_areas_in_error AS total_areas_in_error,
		   ROUND((100*CAST(e.total_areas_in_error AS NUMERIC)/CAST(c.total_areas AS NUMERIC)), 2) AS pct_in_error
	  FROM d, c, e;
DECLARE @areaname AS VARCHAR(30);
DECLARE @area_km2 AS NUMERIC(15,2);
DECLARE @area_km2_calc AS NUMERIC(15,2);
DECLARE @pct_km2_diff AS NUMERIC(15,2);
DECLARE @total_areas AS NUMERIC(15,2);
DECLARE @total_areas_in_error AS NUMERIC(15,2);
DECLARE @pct_in_error AS NUMERIC(15,2);
DECLARE @nrows AS int;
SET @nrows=0;
OPEN c1;
FETCH NEXT FROM c1 INTO @areaname, @area_km2, @area_km2_calc, @pct_km2_diff, @total_areas, @total_areas_in_error, @pct_in_error;
WHILE @@FETCH_STATUS = 0
BEGIN
		SET @nrows+=1;
		IF @nrows = 1 PRINT 'WARNING ' + CAST(@total_areas_in_error AS VARCHAR) + ' areas in error of ' + CAST(@total_areas AS VARCHAR) +
			', ' + CAST(@pct_in_error AS VARCHAR) + 'pct';
		PRINT 'WARNING Area: ' + @areaname + ', area km2: ' + CAST(@area_km2 AS VARCHAR) +  + ', calc: ' +
			CAST(@area_km2_calc AS VARCHAR) + ', diff: ' + CAST(@pct_km2_diff AS VARCHAR);
		FETCH NEXT FROM c1 INTO @areaname, @area_km2, @area_km2_calc, @pct_km2_diff, @total_areas, @total_areas_in_error, @pct_in_error;
END
IF @nrows = 0
	PRINT 'Table: cb_2014_us_county_500k no invalid areas check OK';
ELSE
	IF @pct_in_error < 10 PRINT 'WARNING Table: cb_2014_us_county_500k no invalid areas check WARNING: ' + CAST(@pct_in_error AS VARCHAR) + ' invalid (<10 pct)';
	ELSE
		RAISERROR('Table: cb_2014_us_county_500k no invalid areas check FAILED: %i invalid', 16, 1, @nrows);
CLOSE c1;
DEALLOCATE c1;;

Table: cb_2014_us_county_500k no invalid areas check OK

-- SQL statement 373: Test Turf and DB areas agree to within 1% (Postgres)/5% (SQL server) >>>
DECLARE c1 CURSOR FOR
/*
 * SQL statement name: 	area_check.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Check Turf araa (area_km2) compared to SQL Server calculated area (area_km2_calc)
 *						Allow for 5% error
 *						Ignore small areas <= 15 km2
 * Note:				%% becomes % after substitution
 */
	WITH a AS (
		SELECT areaname,
			   CAST(area_km2 AS NUMERIC(15,2)) AS area_km2,
			   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(15,2)) AS area_km2_calc
		  FROM cb_2014_us_nation_5m
	), b AS (
	SELECT a.areaname,
		   a.area_km2,
		   a.area_km2_calc,
		   CASE WHEN a.area_km2 > 0 THEN 100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2)
				WHEN a.area_km2 = a.area_km2_calc THEN 0
				ELSE NULL
		   END AS pct_km2_diff
	  FROM a
	), c AS (
		SELECT COUNT(areaname) AS total_areas
		  FROM a
	), d AS (
		SELECT b.areaname, b.area_km2, b.area_km2_calc, b.pct_km2_diff
		  FROM b, c
		 WHERE b.pct_km2_diff > 5 /* Allow for 5% error */
		   AND b.area_km2_calc > 15 /* Ignore small areas <= 15 km2 */
	), e AS (
		SELECT COUNT(areaname) AS total_areas_in_error
		  FROM d
	)
	SELECT d.areaname, d.area_km2, d.area_km2_calc, d.pct_km2_diff, c.total_areas AS total_areas, e.total_areas_in_error AS total_areas_in_error,
		   ROUND((100*CAST(e.total_areas_in_error AS NUMERIC)/CAST(c.total_areas AS NUMERIC)), 2) AS pct_in_error
	  FROM d, c, e;
DECLARE @areaname AS VARCHAR(30);
DECLARE @area_km2 AS NUMERIC(15,2);
DECLARE @area_km2_calc AS NUMERIC(15,2);
DECLARE @pct_km2_diff AS NUMERIC(15,2);
DECLARE @total_areas AS NUMERIC(15,2);
DECLARE @total_areas_in_error AS NUMERIC(15,2);
DECLARE @pct_in_error AS NUMERIC(15,2);
DECLARE @nrows AS int;
SET @nrows=0;
OPEN c1;
FETCH NEXT FROM c1 INTO @areaname, @area_km2, @area_km2_calc, @pct_km2_diff, @total_areas, @total_areas_in_error, @pct_in_error;
WHILE @@FETCH_STATUS = 0
BEGIN
		SET @nrows+=1;
		IF @nrows = 1 PRINT 'WARNING ' + CAST(@total_areas_in_error AS VARCHAR) + ' areas in error of ' + CAST(@total_areas AS VARCHAR) +
			', ' + CAST(@pct_in_error AS VARCHAR) + 'pct';
		PRINT 'WARNING Area: ' + @areaname + ', area km2: ' + CAST(@area_km2 AS VARCHAR) +  + ', calc: ' +
			CAST(@area_km2_calc AS VARCHAR) + ', diff: ' + CAST(@pct_km2_diff AS VARCHAR);
		FETCH NEXT FROM c1 INTO @areaname, @area_km2, @area_km2_calc, @pct_km2_diff, @total_areas, @total_areas_in_error, @pct_in_error;
END
IF @nrows = 0
	PRINT 'Table: cb_2014_us_nation_5m no invalid areas check OK';
ELSE
	IF @pct_in_error < 10 PRINT 'WARNING Table: cb_2014_us_nation_5m no invalid areas check WARNING: ' + CAST(@pct_in_error AS VARCHAR) + ' invalid (<10 pct)';
	ELSE
		RAISERROR('Table: cb_2014_us_nation_5m no invalid areas check FAILED: %i invalid', 16, 1, @nrows);
CLOSE c1;
DEALLOCATE c1;;

Table: cb_2014_us_nation_5m no invalid areas check OK

-- SQL statement 374: Test Turf and DB areas agree to within 1% (Postgres)/5% (SQL server) >>>
DECLARE c1 CURSOR FOR
/*
 * SQL statement name: 	area_check.sql
 * Type:				Microsoft SQL Server T/sql anonymous block
 * Parameters:
 *						1: geometry column; e.g. geom_11
 *						2: table name; e.g. cb_2014_us_county_500k
 *
 * Description:			Check Turf araa (area_km2) compared to SQL Server calculated area (area_km2_calc)
 *						Allow for 5% error
 *						Ignore small areas <= 15 km2
 * Note:				%% becomes % after substitution
 */
	WITH a AS (
		SELECT areaname,
			   CAST(area_km2 AS NUMERIC(15,2)) AS area_km2,
			   CAST((geom_9.STArea()/(1000*1000)) AS NUMERIC(15,2)) AS area_km2_calc
		  FROM cb_2014_us_state_500k
	), b AS (
	SELECT a.areaname,
		   a.area_km2,
		   a.area_km2_calc,
		   CASE WHEN a.area_km2 > 0 THEN 100*(ABS(a.area_km2 - a.area_km2_calc)/area_km2)
				WHEN a.area_km2 = a.area_km2_calc THEN 0
				ELSE NULL
		   END AS pct_km2_diff
	  FROM a
	), c AS (
		SELECT COUNT(areaname) AS total_areas
		  FROM a
	), d AS (
		SELECT b.areaname, b.area_km2, b.area_km2_calc, b.pct_km2_diff
		  FROM b, c
		 WHERE b.pct_km2_diff > 5 /* Allow for 5% error */
		   AND b.area_km2_calc > 15 /* Ignore small areas <= 15 km2 */
	), e AS (
		SELECT COUNT(areaname) AS total_areas_in_error
		  FROM d
	)
	SELECT d.areaname, d.area_km2, d.area_km2_calc, d.pct_km2_diff, c.total_areas AS total_areas, e.total_areas_in_error AS total_areas_in_error,
		   ROUND((100*CAST(e.total_areas_in_error AS NUMERIC)/CAST(c.total_areas AS NUMERIC)), 2) AS pct_in_error
	  FROM d, c, e;
DECLARE @areaname AS VARCHAR(30);
DECLARE @area_km2 AS NUMERIC(15,2);
DECLARE @area_km2_calc AS NUMERIC(15,2);
DECLARE @pct_km2_diff AS NUMERIC(15,2);
DECLARE @total_areas AS NUMERIC(15,2);
DECLARE @total_areas_in_error AS NUMERIC(15,2);
DECLARE @pct_in_error AS NUMERIC(15,2);
DECLARE @nrows AS int;
SET @nrows=0;
OPEN c1;
FETCH NEXT FROM c1 INTO @areaname, @area_km2, @area_km2_calc, @pct_km2_diff, @total_areas, @total_areas_in_error, @pct_in_error;
WHILE @@FETCH_STATUS = 0
BEGIN
		SET @nrows+=1;
		IF @nrows = 1 PRINT 'WARNING ' + CAST(@total_areas_in_error AS VARCHAR) + ' areas in error of ' + CAST(@total_areas AS VARCHAR) +
			', ' + CAST(@pct_in_error AS VARCHAR) + 'pct';
		PRINT 'WARNING Area: ' + @areaname + ', area km2: ' + CAST(@area_km2 AS VARCHAR) +  + ', calc: ' +
			CAST(@area_km2_calc AS VARCHAR) + ', diff: ' + CAST(@pct_km2_diff AS VARCHAR);
		FETCH NEXT FROM c1 INTO @areaname, @area_km2, @area_km2_calc, @pct_km2_diff, @total_areas, @total_areas_in_error, @pct_in_error;
END
IF @nrows = 0
	PRINT 'Table: cb_2014_us_state_500k no invalid areas check OK';
ELSE
	IF @pct_in_error < 10 PRINT 'WARNING Table: cb_2014_us_state_500k no invalid areas check WARNING: ' + CAST(@pct_in_error AS VARCHAR) + ' invalid (<10 pct)';
	ELSE
		RAISERROR('Table: cb_2014_us_state_500k no invalid areas check FAILED: %i invalid', 16, 1, @nrows);
CLOSE c1;
DEALLOCATE c1;;

Table: cb_2014_us_state_500k no invalid areas check OK


--
-- EOF