[GIS] How to convert from SQL Server geometry BLOB to something else

geometrygeometry-conversionsql server

I have a CSV data file from a 3rd party that is an exported SQL Server table. They simply did a select * from foo and output the result to a text file and sent it over.

In their table is column of Geometry type, so in my raw text I have something like "0xE610000010C47…", etc. At the moment I've loaded it into a table in SQL Server as an nvarchar.

I anticipated I would be able to reverse back into a Geometry field on my end, but that doesn't seem to be so easy. STGeomFromWKB doesn't work because it's not actually a WKB. I can't cast the string as Geometry because it complains that it's not a WKT.

So, is there any way I can get this value into SQL Server as if it is a normal Geometry BLOB? Can I tell SQL Server to treat it as such?

I found this link which helped at least answer my question about what is in SQL Server, but didn't get me all the way there:
what is the format of Geometry data type of SQLServer 2008

Best Answer

When you import the data into SQL Server, put it into a VARBINARY(MAX) column. You should then be able to CAST this as a Geometry or Geography as required. You will need to be careful that the string 0xE6 ... is not changed during the import.

Another option is to do a dynamic query to get the selection. I put a couple of conversion examples below.

-- As a varchar and binary
DECLARE @NV AS NVARCHAR(MAX) = '0xE610000001040E0000002AA57BA76F5446C027B8FD971024654007517714795446C00C42473D1624654094CFCDE3795446C0D3F576B91624654068507E9C7A5446C0D7BE805E18246540F2FC444A7C5446C0E93DDF6019246540B4CA4C697D5446C0D5DF5C0D1A2465401A0923AC7C5446C08183DE3F1A2465407599E1907B5446C0E2A8818B1A24654058B4805A7A5446C0A70261DE1A24654089729F5C775446C072080BDD1B2465401AAC24A8745446C057CB10FE1C2465403D16A5446E5446C05A20FEE21A246540658BA4DD685446C00907FFA3172465402AA57BA76F5446C027B8FD971024654001000000020000000001000000FFFFFFFF0000000003' 
DECLARE @NB AS VARBINARY(MAX) = 0xE610000001040E0000002AA57BA76F5446C027B8FD971024654007517714795446C00C42473D1624654094CFCDE3795446C0D3F576B91624654068507E9C7A5446C0D7BE805E18246540F2FC444A7C5446C0E93DDF6019246540B4CA4C697D5446C0D5DF5C0D1A2465401A0923AC7C5446C08183DE3F1A2465407599E1907B5446C0E2A8818B1A24654058B4805A7A5446C0A70261DE1A24654089729F5C775446C072080BDD1B2465401AAC24A8745446C057CB10FE1C2465403D16A5446E5446C05A20FEE21A246540658BA4DD685446C00907FFA3172465402AA57BA76F5446C027B8FD971024654001000000020000000001000000FFFFFFFF0000000003

-- Failing conversions
SELECT CAST(@NV AS Geometry)
SELECT CAST(CAST(@NV AS VARBINARY(MAX)) AS Geometry)
-- Correct conversion
SELECT CAST(@NB AS Geometry)
EXEC('SELECT CAST(' + @NV + ' AS Geometry)')