Go to content Go to navigation and search

Home

Current SQL Server Blog Articles

    STGeometryTypes: Extracting all geometry type string values from complex geometry
    STDensify: Densify (m)LineString or (m)Polygon geometry objects
    STInsertN: Insert single vertex into a geometry
    STUpdateN: Update (replace) a single vertex within a geometry object.
    STUpdate: Replace all points equal to the supplied point with replacement point.
    STDeleteN: Delete single vertex from geometry
    STDelete: Deleting vertices in geometry objects
    STFlipVectors: Normalize direction of linestring vectors
    STConvertToLineString: Extract LineStrings in GeometryCollection to create LineString
    STLine2Cogo: Converting LineStrings to COGO XML
    STCogo2Line: Creating (Multi)LineStrings geometries from COGO XML instructions
    STVectorize: Break Linestring/Polygon elements into 2 point vectors (or 3 point circular curves)
    STScale: Function to Scale a geometry object
    TSQL String Tokenizer Function for SQL Server
    STGeometry2MBR/STGeography2MBR: Compute and return MBR ordinates
    generate_series for SQL Server 2008
    STExtractPolygon: Extract Polygons from result of STIntersection in SQL Server Spatial
    STRound: Function to round ordinates of a SQL Server Spatial geometry object
    STExtract: Extract elements of a geometry object
    STNumRings: Counting number of polygon rings
    STFilterRings: Removing rings from Polygon based on area.
    STMove: Function to Move a geometry object in SQL Server Spatial
    STCentroid*: Alternate Functions for Compute a Centroid
    STRotate: Function to rotate a geometry object in SQL Server Spatial
    STVertices: Wrapper over STDumpPoints
    STMorton: Creating a Morton number Space Key value for grid square
    Gridding a geometry or geography object (SQL Server Denali)
    On hinting spatial indexes
    RandomSearchByExtent: Random Search Procedure (2008 Spatial)
    COGO: Convert DMS String to decimal degrees floating point number.
    COGO: Converting (Google Earth) Formatted Longitude/Latitude points to decimal degrees (SQL Server)
    COGO: Convert Degrees, Minutes and Seconds values to Decimal Degrees
    COGO: DD2DMS Formatting a latitude/longitude decimal degree value
    COGO: Create point from bearing and distance
    COGO: Compute number of vertices required to stroke circle or circular arc
    COGO: Calculating the bearing between two points (SQL Server 2008 Spatial)
    COGO: Compute arc length subtended by angle centre of circle
    COGO: Compute chord length of segment of a circle (arc)
    COGO: Computing Arc To Chord (Arc2Chord) Separation
    COGO: Creating a stroked polygon from a circle's centre x,y and radius
    COGO: Finding centre and radius of a curve defined by three points: FindCircle function
    CheckRadii: Identifying Tight Radius Curves sections within LineString geometry data
    Generating random point data for SQL Server 2008 Spatial
    New Presentation on Active (Searchable) Spatial Metadata for SQL Server 2008 Spatial and FreeText
    STisGeo: Checking if a column in a table or a view is of type geometry or geography
    Vectorising geometry objects in SQL Server 2008
    STMBR2Geometry/STMBR2Geography functions
    Extracting geometry types from geometry/geography objects in SQL Server 2008
    Getting the number of coordinate dimensions of a geometry/geography object in SQL Server 2008
    STDumpPoints: A Function that Dumps the Vertices/Points in a geometry
    toGeography and toGeography Conversion Functions for SQL Server 2008 Spatial
    Write text file with spatial data from SQL Server 2008
    Loading Shapefiles into Geography type column in SQL Server 2008
    Tip #6: Correcting invalid geometries
    Tip #5: Where or where has my little column gone
    Tip #4: What Coordinate System is that?
    Tip #3: What object is that?
    Tip #2: Spatial Indexing and Primary Keys
    Tip #1: SQL Server 2008 "Katmai" - Setting SRIDs

Search

    Browse

RSS / Atom

Email me

textpattern

Creative Commons License
All Blog Articles, Data Models and Free Source Code by Simon Greener, The SpatialDB Advisor is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

STisGeo: Checking if a column in a table or a view is of type geometry or geography

Monday November 23 2009 at 09:45

KeywordsSTisGeo geography table column
Summary

Function that tests if geometry / geography column in a table is of type geography

Sometimes things are simple and prosaic rather than clever and complicated.

Building solutions in TSQL requires one to build a prior collection of handy functions before one can be really productive.

Here is a function I use called isGeo which if provided the name of a table/view and a column name returns 1 (true) if the column exists and is of type geometry or geography.

  1. USE [GISDB]  /* Replace this with the name of your database */
  2. GO
  3. CREATE FUNCTION [dbo].[STisGeo] (
  4.   @schema_name nvarchar(128),
  5.   @object_name nvarchar(128),
  6.   @column_name nvarchar(128)
  7. )
  8. RETURNS INTEGER
  9. WITH EXECUTE AS CALLER,
  10.      RETURNS NULL ON NULL INPUT
  11. AS
  12. BEGIN
  13.   DECLARE @v_result VARCHAR(15);
  14.     SELECT @v_result=a.column_type
  15.       FROM (SELECT sc.name AS schema_name,
  16.                    ta.name AS object_name,
  17.                    co.name AS column_name,
  18.                    ty.name AS column_type,
  19.                    'TABLE' AS object_type
  20.               FROM sys.TABLES ta
  21.                    JOIN sys.schemas sc ON sc.schema_id = ta.schema_id
  22.                    JOIN sys.COLUMNS co ON ta.object_id = co.object_id
  23.                    JOIN sys.types ty   ON co.user_type_id = ty.user_type_id
  24.              WHERE ty.name IN ('geography','geometry')
  25.              UNION ALL
  26.             SELECT sc.name AS schema_name,
  27.                    va.name AS object_name,
  28.                    co.name AS column_name,
  29.                    ty.name AS column_type,
  30.                    'VIEW' AS object_type
  31.               FROM sys.views va
  32.                    JOIN sys.schemas sc ON sc.schema_id = va.schema_id
  33.                    JOIN sys.COLUMNS co ON va.object_id = co.object_id
  34.                    JOIN sys.types ty   ON co.user_type_id = ty.user_type_id
  35.              WHERE ty.name IN ('geography','geometry')
  36.             ) a
  37.         WHERE a.schema_name = @schema_name
  38.           AND a.object_name = @object_name
  39.           AND a.column_name = @column_name ;
  40.     RETURN CASE WHEN @v_result IS NULL       THEN -1
  41.                 WHEN @v_result = 'geography' THEN  1
  42.                 ELSE 0
  43.            END;
  44. END;

Now, some tests…

  1. CREATE TABLE dbo.foo (foo_id INTEGER, geog geography, geom geometry);
  2. SELECT dbo.STISGEO('dbo',NULL,'geog') AS isGeo;
  3. isGeo
  4. NULL
  5. SELECT dbo.STISGEO('dbo','foo','geog') AS isGeo;
  6. isGeo
  7. 1
  8. SELECT dbo.STISGEO('dbo','foo','geom') AS isGeo;
  9. GO
  10. isGeo
  11. 0
  12. CREATE VIEW dbo.vw_foo AS SELECT foo_id, geog FROM dbo.foo;
  13. SELECT dbo.STISGEO('dbo','foo','geom') AS isGeo;
  14. isGeo
  15. 0
  16. SELECT dbo.STISGEO('dbo','foo','geog') AS isGeo;
  17. isGeo
  18. 1
  19. DROP VIEW  dbo.vw_foo;
  20. DROP TABLE dbo.foo;

I hope this helps someone.

Creative Commons License

post this at del.icio.uspost this at Diggpost this at Technoratipost this at Redditpost this at Farkpost this at Yahoo! my webpost this at Windows Livepost this at Google Bookmarkspost this to Twitter

Comment [4]

Information_Schema nazi at your disposal :)

Simon — what’s wrong with doing this instead of all that messy JOIN stuff?

SELECT table_schema, column_name,data_type FROM information_schema.columns
WHERE DATA_TYPE IN(‘geometry’, ‘geography’);

It will catch both tables and views.

Regina 24 November 2009, 15:36 #

Regina,

Of course you are perfectly right to suggest use of Information_Schema. And, yes, it is more succinct.

Still, I didn’t know that geometry and geography were data types from the Information_Schema SQL standard!

regards
Simon

Simon 25 November 2009, 01:20 #

I think the standard says you have to list the data_type and for standard datatypes you have to call it a specific name even if you don’t call it that natively. Actually not sure it even says that. Anyrate I think most databases that support the information schema — always list the data type even if its specific to that brand of db.

MySQL — there is only one information_schema — so you have to be a bit careful — as their schema is really the database (much like Oracle :) guess another reason why Oracle and MySQL are a good pair) — so their catalog field is blank but the same query as above will work in MySQL if you include table_schema = database_name

PostgreSQL / PostGIS doesn’t quite work without more change. Reason is PostGIS is not a built in datatype.

So — the data_type field contains a useless ‘USER-DEFINED

and the real field you want to query is the udt_name (which like for varchar will have varchar (instead of character varying — which varchar is nicer anyway)

So your equivalent query in PostGIS would be

SELECT table_schema, table_name, column_name, udt_name As data_type
FROM information_schema.columns
WHERE udt_name IN(‘geometry’, ‘geography’);

Still pretty close though :)

Regina 25 November 2009, 13:22 #

Regina,

The udt_name field is only available in PostgreSQL and not SQL Server 2008.

I have used both the SQL Server 2008 proprietary catalog and Information_Schema in coding other functions so I am not against using it here.

In summary, I don’t disagree with using the shorter Information_Schema based approach. The physical implementation details are hidden from the user via use of the isGeo() function anyway.

regards
Simon

Simon 27 November 2009, 01:42 #