sqlsql-serverspatial-query

Function that calls assembly, how can I update the parameter?


I have the below code in SQL. This is called by passing a geometry object, as in dbo.MakeValidGeographyFromGeometry(geom):

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER FUNCTION [dbo].[MakeValidGeographyFromGeometry](@inputGeometry [geometry])
RETURNS [geography] WITH EXECUTE AS CALLER
AS 
EXTERNAL NAME [SQLSpatialTools].[SQLSpatialTools.Functions].[MakeValidGeographyFromGeometry]

We frequently have errors in the geometry which causes this function to have issues. As such, I'd like to update the @inputGeometry parameter as it passes through. I know the code that updates a geometry, but don't know how to implement it here.

In a function like this, how can we update the parameter being passed through?


Solution

  • Since one cannot combine TSQL and assembly call in one function, i suggest creating a wrapper function which calls your assembly function. The wrapper function should have the original name to avoid disruption and code rewriting.

    The basic steps are:

    1. Create a new assembly function called MakeValidGeographyFromGeometryInternal that is a copy of the current assembly function. Make sure to take note of the existing permissions so you can transfer them properly
    2. Drop the current assembly function. This is needed because usually SQL Server disallows changing the function "type" by ALTER.
    3. Create a wrapper function called MakeValidGeographyFromGeometry that does whatever processing you need and then calls MakeValidGeographyFromGeometryInternal. Make sure to take care of permissions needed if any.

    This should allow you to keep the calling code as it was.