4

我有一个与该类型不兼容的 sql 语句,Sql Geometry因此我正在尝试对其进行修改以使其工作。

它的基本要点是这样的:

Select distinct A,B,C,D,SHAPE FROM TABLE1 UNION SELECT A,B,C,D,SHAPE FROM TABLE2

因此,对两个不同(但相似)表的复杂不同语句的结果是联合的。

问题是SQL Geometry类型(SHAPE 字段)不能包含在不同的语句中,因为它不是可比较的类型。

我可以SHAPE从参与联合的两个子查询中删除该字段。但我想在解析这些子查询后取回它。SHAPE如果我知道 A 列的值,我可以获得该字段。

所以我的问题是:如何从两个子查询中的不同语句中删除一个字段,然后通过将其加入另一列 (A) 中将该字段(连同其余字段)返回结果集中?

4

3 回答 3

4

您可以转换为 VARBINARY(MAX),然后再转换回来。

create table tbl1 ( ID int, a int, b char(3), d geometry );
create table tbl2 ( ID int, a int, b char(3), d geometry, other float );
insert tbl1 (ID, a, b, d) values
    (1, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0)),
    (2, 3, 3, geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0)),
    (3, 4, 3, geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0)),
    (4, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 250 0, 150 150, 0 150, 0 0))', 0)),
    (5, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 350 0, 150 150, 0 150, 0 0))', 0))
insert tbl2 (ID, a, b, d) values
    (6, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0)), -- same as tbl1.ID=1
    (7, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 950 0, 150 150, 0 150, 0 0))', 0)),
    (8, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 350 0, 150 150, 0 150, 0 0))', 0)); -- same as tbl1.ID=5

SELECT A, B, cast(c as geometry) c
FROM
(
    Select A,B,cast(D as varbinary(max)) c FROM tbl1
    UNION
    SELECT A,B,cast(D as varbinary(max)) FROM tbl2
) X;
于 2012-12-06T21:06:18.330 回答
0
CREATE VIEW GeometryView1 AS
  SELECT A,B,C,D,SHAPE AS tabId FROM TABLE1 
  UNION SELECT A,B,C,D,SHAPE FROM TABLE2;

CREATE VIEW GeometryView2 AS
  SELECT DISTINCT A,B,C,D FROM (
  SELECT A,B,C,D AS tabId FROM TABLE1 
  UNION SELECT A,B,C,D FROM TABLE2) x;

SELECT DISTINCT v2.A,v2.B,v2.C,v2.D,v1.SHAPE FROM GeometryView2 v2 , GeometryView1 v1
WHERE v2.A=v1.A AND v2.B=v1.B AND v2.C=v1.C AND v2.D=v1.D 
于 2012-12-06T21:22:48.083 回答
0

这行得通吗?

with cte as (
Select distinct A,B,C,D FROM TABLE1
)
select c.A,c.B,c.C,c.D,t.SHAPE 
FROM cte as c
inner join TABLE1 as t
   on c.A = t.A
UNION 
SELECT A,B,C,D,SHAPE FROM TABLE2
于 2012-12-07T02:42:10.590 回答