Wednesday, May 16, 2012

Shapefiles to SQL Server


I'm using Ogr2Ogr 1.8 to directly upload Shapefiles to SQL Server. Ive followed the directions of SQL Server Import using Ogr2Ogr to Build Ogr2Ogr 1.8 command line utilities--for only ogr2ogr version 1.7 is currently built and distributed. 
I've copied the column names from the Shapefile to a new table in SQL Server, including data types. Wrote the code in a PowerShell script and gave it a run and I got allot of errors. Including:

ERROR 1: Column ogr_geometry requested for geometry, but it does not exist.
ERROR 1: Error creating field allot_, [Microsoft][ODBC SQL Server Driver][SQL Server]Column names in each table must be unique. Column name 'allot_' in table 'dbo.ASLDGrazingAllotments' is specified more than once.
ERROR 1: INSERT command for new feature failed. [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column 'ALLOT_', table 'SpatialCollection.dbo.ASLDGrazingAllotments'; column does not allow nulls. INSERT fails.


I found that there is some bad data--including duplicate keys and nulls in the 2,000 records.
I changed the primary key in the database to an new column with an auto-increment identity.
I also created a geometry column.

--no luck with the dataset I need, but I made a practice dataset with one polygon and it ran beautifully with the following simple Powershell Script:

#POWERSHELL
$inputFile = "**filename**"
$connString = "MSSQL:server=.\SQLEXPRESS;database=SpatialCollection;trusted_connection=yes;table=ASLDGrazingAllotments"

# -lco 'layer creation option NAME=VALUE'
function MyOgr {
ogr2ogr -overwrite -f MSSQLSpatial -lco “GEOM_TYPE=geometry” "GEOM_NAME=geom" -a_srs "EPSG:26912" $connString $inputFile
}
function MyOgrLess {
ogr2ogr -overwrite -f MSSQLSpatial $connString $inputFile -skipfailures
}
function OgrTestConnection {
ogrInfo $connString
}
function OgrTestInput {
ogrInfo $inputFile -fields=YES
}
#geom={YES/NO/SUMMARY} yes will give you WKT
function OgrGetAll {
ogrInfo $inputFile -fields=YES -al -geom=YES
}
function OgrHelp {
    explorer.exe http://gis-lab.info/docs/gdal/gdal_ogr_user_docs.html
}
MyOgrLess
Ok, I deleted all my tables, added the -skipfailures arguement, ran it again, and it worked beautifully. Heres somne pictures of the results:

All three new tables into the database

SQL Server Management Studio actually allows you to view your records spatially!--AWESOME

No comments:

Post a Comment