SqlDbType and Geography

9

当我的列是地理类型时,我应该使用哪个SqlDbType枚举?我使用的是MS SQL Server 2008 R2。

具体而言,我正在寻找以下内容:

// ADO.net - what do I use for the SqlDbType when it's defined 
// as Geography in the stored proc
SqlCommand command = new SqlCommand();
command.CommandText = "dbo.up_Foobar_Insert";
command.CommandType = CommandType.StoredProcedure;

command.Parameters.Add("@SomeGeographyType", SqlDbType.????);
3个回答

13

SqlGeography是由SQL Server实现为CLR用户定义类型,因此您可以执行类似以下代码的操作:

SqlGeography geo = // Get the geography from somewhere...

using (SqlCommand command = 
    new SqlCommand(@"dbo.up_Foobar_Insert", connection))
    command.Parameters.Add(new SqlParameter("@Point", geo) { UdtTypeName = "Geography" });
    command.ExecuteNonQuery();
}

如果你在做桌面应用程序,那么就比较容易了。在Code Project上有一个很好的示例,展示了如何创建一个SQL几何图形查看器,它适用于桌面或Web应用。

要直接使用SQLGeometry或SQLGeography,需要引用Microsoft.SqlServer.Types.dll。该文件位于SQL Server Install /100/SDK/Assemblies目录下。


2
还有一个包含所需程序集的NuGet包:Microsoft.SqlServer.Types(Spatial) - Sam

0

更新

试试这个:

//define parameter
command.Parameters.Add("@shape", SqlDbType.NVarChar);
//
//code in between omitted
//
//set value of parameter
command.Parameters["@shape"].Value = feature.Geometry.AsText();

摘自使用SqlCommand插入SQL 2008几何数据


0

当我尝试使用 SqlDbType.NVarChar 时,我收到了一个错误信息

无法将地理位置参数值转换为字符串

解决这个问题的方法是使用 SqlDbType.Udt

var pgeo = cmd.Parameters.Add("@GeoLocation", SqlDbType.Udt);
pgeo.UdtTypeName = "Geography";

然后稍后,在循环中,我设置了参数的值:

var ss = new SqlString(objValue.ToString());
var sc = new SqlChars(ss);
var geocode = SqlGeography.STPointFromText(sc, 4326);
cmd.Parameters["@GeoLocation"].Value = geocode;

注意:这需要 Microsoft.SqlServer.TypesSystem.Data.SqlTypes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接