使用外键SQL插入数据

时间:2016-08-07 21:52:04

标签: sql-server foreign-keys foreign-key-relationship

我有两个SQL表ctgl_geometryctgl_vertices

ctgl_geometry将存储点如何相互连接的几何,因此它有一个id,一个值,顶点数和一个外键来链接id以获取值的列表几何

CREATE TABLE ctgl_geometry (
  Id                    int primary key,
  otherVal              int,
  NoVertices            int,
  vertexID              int 
);
create table ctgl_vertices
(
  Id         int primary key,
  GeometryId int,
  val        int
);

例如,如果有一个长度为5的顶点{0,1,6,5,4} ,我会将它存储在顶点表中,如

INSERT INTO ctgl_vertices VALUES 
(1,101,0),
(2,101,1),
(3,101,6),
(4,101,5),
(5,101,4);

并且几何形状如下:

INSERT INTO ctgl_geometry VALUES 
(1, 10,5,101);  

101 是了解清单的链接。

但如果我不知道身份值(示例中的 ),我不知道如何保存值

所以我在考虑使用IDENT_CURRENT知道最后插入的顶点表值,如:

SELECT  IDENT_CURRENT('ctgl_vertices ') + IDENT_INCR('ctgl_vertices ');

,结果将其分配给ctgl_geometry vertexID

的外键

但我认为有更好的方法可以做到这一点......

如何插入顶点列表然后将值赋给几何?

我也在使用此查询来检索值:

select g.NoVertices,v.val from ctgl_geometry g 
      inner join ctgl_vertices v
on g.vertexID = v.GeometryId where g.otherVal = 10; 

并获取

NoVertices  val
5   0
5   1
5   6
5   5
5   4
4   1
4   2
4   7
4   6
4   2
4   3
4   8
4   7
4   4
4   5
4   10
4   9
4   5
4   6
4   11
4   10
4   6
4   7
4   12
4   11
4   7
4   8
4   13
4   12

Please take a look at fiddle

1 个答案:

答案 0 :(得分:1)

您的表架构需要一些认真的关注。您在逻辑上定义了外部关系,但实际上并没有实现它们。

您的引用列必须在其上定义外键约束,在您的情况下,它是GeometryId

被引用的列必须是主键列,在您的情况下为vertexID

考虑到这些建议,表格模式应该类似......

CREATE TABLE ctgl_geometry (
  Id                    int  ,
  otherVal              int,
  NoVertices            int,
  vertexID              int IDENTITY(1,1) NOT NULL primary key
);
GO
create table ctgl_vertices
(
  Id         int primary key,
  GeometryId int REFERENCES ctgl_geometry(vertexID),
  val        int
);
GO

现在,一旦您逻辑更正了表模式,您将使用SCOPE_IDENTITY()获取ctgl_geometry表中标识列生成的最新标识值,并使用该值将行插入ctgl_vertices 1}}表。

像......一样......

Declare @NewID INT;

INSERT INTO ctgl_geometry (Id , otherVal, NoVertices)
VALUES (1, 10,5); 

 SET @NewID = SCOPE_IDENTITY();


INSERT INTO ctgl_vertices (Id, GeometryId  ,Val)
VALUES 
   (1,@NewID,0),
   (2,@NewID,1),
   (3,@NewID,6),
   (4,@NewID,5),
   (5,@NewID,4);
相关问题