Perhaps like so: -
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlXml ExportToKml(SqlGeography g)
{
if (g == null || g.IsNull)
return new SqlXml();
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
KeyholeMarkupLanguageGeography sink = new KeyholeMarkupLanguageGeography(writer);
g.Populate(sink);
sink.FinalizeKMLDocument();
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
return new SqlXml(stream);
}
Can also be added to register scripts as follows: -
create function ExportToKml(@g geography) returns xml
as external name SQLSpatialTools.[KMLFunctions].ExportToKml
go