Skip to content Skip to sidebar Skip to footer

Generate View With X And Y From Geometry Type

In sql-server-2012 I want to generate view with all points from geometry type. How can I do this? View example GeomKey | X | Y --------+----+----- 1 | X1 | Y1 1 | x2 |

Solution 1:

I don't think you can do this in a view but you can create a table-valued user defined function (a function that returns a table) to get what you want.

This example uses a table defined as

CREATE TABLE GeoTable (GeomKey int, vector GEOMETRY)

which stores different geometry types (in the example I linked below I used POINT, MULTIPOINT, LINESTRING and POLYGON).

CREATE FUNCTION dbo.GetVertices()
RETURNS @ret TABLE (GeomKey INT, X INT, Y INT, PointNo INT)
AS
BEGIN
    DECLARE @max INT
    SET @max = (SELECT MAX(vector.STNumPoints()) FROM GeoTable) 

    ;WITH Sequence(Number) AS
    (
        SELECT 1 AS Number
        UNION ALL
        SELECT Number + 1
        FROM Sequence
        WHERE Number < @max
    )
    INSERT INTO @ret 
    SELECT
        gt.GeomKey
        ,gt.vector.STPointN(nums.number).STX AS X
        ,gt.vector.STPointN(nums.number).STY AS Y
        ,nums.number AS PointNo
    FROM GeoTable gt, Sequence nums
    WHERE nums.number <= gt.vector.STNumPoints()
    RETURN
END;

See this sample SQL Fiddle for a complete working example.


Post a Comment for "Generate View With X And Y From Geometry Type"