MS SQL 2005 或 2008 中多个标识列的自动增量

发布于 2024-09-07 01:12:40 字数 161 浏览 5 评论 0 原文

我想在 MS SQL 中有两个不同的表,例如用户和组,都带有标识列。可以在两个标识列上创建自动增量吗?我想要第三个表,其中包含这两个表的公共信息,并且我想识别唯一记录。

在Oracle中是SEQUENCE。

有可能做到吗?

谢谢,

马丁·皮尔奇

I want to have two different tables in MS SQL, for example users and groups, both with identity column. It is possible to create auto increment over two identity columns? I want to have third table with common informations to these two tables and I want to identify unique record.

In Oracle is SEQUENCE.

It is possible to do it?

Thanks,

Martin Pilch

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

dawn曙光 2024-09-14 01:12:40

Afaik,SQL Server 没有可以在多个表中使用命名身份的概念(参见 Oracle SEQUENCE

您有几个选项来区分来自两个表的数据

  • 使用 GUID 作为 ID 列在两个表中。
  • 在第三个表中,操作两个表之一的 ID,再次产生唯一 ID(例如乘以 -1)。 我假设您的第三个表将是其他两个表的视图。
  • 重新思考您的设计,了解为什么需要这样的构造。

如果设计无法更改,那么我会优先选择使用 GUID。

Afaik, SQL Server does not have a concept where you can use a named identity in multiple tables (cfr. Oracles SEQUENCE)

You have a few options to differentiate the data coming from both tables

  • Use a GUID as your ID column in both tables.
  • In your third table, manipulate the ID of one of both tables resulting again in a unique ID (Multiply with -1 for instance). I am assuming your third table would be a view on both other tables.
  • Rethink your design as to why you would need such a construct.

If the design can't be changed, using a GUID would be my choice of preference.

喜你已久 2024-09-14 01:12:40

我不确定您到底在寻找什么,但您可以使用 IDENTITY 属性:

CREATE TABLE new_employees
(
 id_num int IDENTITY(1,1),
 fname varchar (20),
 minit char(1),
 lname varchar(30)
);

在上面的示例中(取自链接页面),id_num 字段将自动递增,以种子开始1 并递增 1。

您可以在每个表上都有一个这样的字段,以及链接这两个表的多对多表。

I am not sure exactly what you are looking for, but you can have auto increment fields in SQL Server using the IDENTITY property:

CREATE TABLE new_employees
(
 id_num int IDENTITY(1,1),
 fname varchar (20),
 minit char(1),
 lname varchar(30)
);

In the above example (taken from the linked page), the id_num field will auto increment, starting with a seed of 1 and incrementing it by 1.

You can have such a field on each table and a many-to-many table that links the two.

弃爱 2024-09-14 01:12:40

对于 SQL Server,您拥有身份属性

您的第三个表应通过外键引用用户和组。

要实现第三个表中两列的唯一性,只需使用唯一约束,如下所示:

CREATE TABLE Third (
  id_user INT references Users(id),
  id_group INT references Groups(id),
  CONSTRAINT user_group_unique UNIQUE(id_user, id_group)
);

For SQL Server you got Identity property.

Your third table should reference users and groups via foreign key.

To achieve uniqueness of both columns in your third table, simply use unique constraint, like this:

CREATE TABLE Third (
  id_user INT references Users(id),
  id_group INT references Groups(id),
  CONSTRAINT user_group_unique UNIQUE(id_user, id_group)
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文