【问题标题】:SQL Server Geography type creates multiple types for the same variableSQL Server 地理类型为同一个变量创建多个类型
【发布时间】:2015-02-12 12:12:14
【问题描述】:

我开始使用 Microsoft SQL Server Geography 数据类型。一切正常,但我遇到了一个小问题。

我首先创建了一个包含 2 列的表(ClientId 不是主要的)路由:ClientId (int) 和 Zone (geography)

CREATE TABLE [dbo].[routes]
(
    [ClientId] [int] NOT NULL,
    [Zone] [geography] NULL,
)

我运行了以下脚本(302624121 是新创建的表):

SELECT
    o.id as 'Id', c.name as 'Name', t.name AS 'Type', 
    c.length AS 'Length'
FROM 
    sys.sysobjects as o 
INNER JOIN 
    sys.syscolumns AS c ON o.id = c.id 
INNER JOIN 
    sys.systypes AS t ON c.xtype = t.xtype 
WHERE 
    (o.id = 302624121)

瞧,这就是我得到的:

302624121   ClientId    int 4
302624121   Zone    hierarchyid -1
302624121   Zone    geometry    -1
302624121   Zone    geography   -1

该区域已创建 3 次!!!!

接下来我添加了一个存储过程来从上表中选择数据,其中给定点包含在客户的地理范围内。

Create proc [dbo].[up_RoutesSelectByGeography]
    @ClientId int,
    @Zone geography
as
begin
    SELECT [ClientId], [Zone]         
      FROM [dbo].[Routes]         
      where ClientId = @ClientId and [Zone].STContains(@Zone) = 1 
end

我使用过程的 id 运行了以下查询:

SELECT
    o.id as 'Id', c.name as 'Name', 
    t.name AS 'Type', c.length AS 'Length'
FROM 
    sys.sysobjects as o 
INNER JOIN 
    sys.syscolumns AS c ON o.id = c.id 
INNER JOIN 
    sys.systypes AS t ON c.xtype = t.xtype 
WHERE 
    (o.id = 334624235)

对于同一个变量,我总是得到 3 种类型:

334624235   @ClientId   int 4
334624235   @Zone   hierarchyid -1
334624235   @Zone   geometry    -1
334624235   @Zone   geography   -1

这个问题给我带来了一个问题,因为我无法将字段名称与变量映射,因为我三次获得相同的变量名称。

对正在发生的事情有任何启示吗?哪些变量映射到我的 c#??

【问题讨论】:

  • 不是问题的一部分,但值得您使用 sys.objectssys.columnssys.types,而不是 sys.sysobjectssys.syscolumnssys.systypes -包含系统视图sys.sys... 只是为了向后兼容,将从 SQL Server 的未来版本中删除。

标签: sql-server sqlgeography


【解决方案1】:

问题在于hierarchyidgeometrygeography 在 sys.systypes 表中都有相同的 xtype 值:

select name, xtype, xusertype from sys.systypes where xtype = 240
/*
name          xtype   xusertype
------------- ------- ---------
hierarchyid   240     128
geometry      240     129
geography     240     130
*/

因此,当将此表连接到查询中的 syscolumns 时,您只能通过列 xtype 获得笛卡尔积。为避免这种情况,请在连接中包含 xusertype 列:

select o.id as 'Id', c.name as 'Name', t.name AS 'Type', c.length AS 'Length' 
FROM sys.sysobjects as o 
INNER JOIN sys.syscolumns AS c ON o.id = c.id 
INNER JOIN sys.systypes AS t ON c.xtype = t.xtype AND c.xusertype = t.xusertype  -- here!
WHERE (o.id = 334624235)

【讨论】:

  • 谢谢丹。做到了!现在我有正确的数据了。
  • “为避免这种情况,请在连接中包含 xusertype 列”。或者,您知道,停止使用已弃用的系统表。 DMV 是在 SQL 2005 中引入的(在撰写本文时是 10 年前)!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
相关资源
最近更新 更多