具有唯一键的SQL表 [英] SQL Table with Unique Key

查看:103
本文介绍了具有唯一键的SQL表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个如下表
ID,帐号,类型

Hi i need a table as follows
ID, Accno, Type

1 , 1 , 1
1 , 1 , 2
1 , 1 , 3
1 , 2 , 1 it can not be allowed
2 , 1 , 1 it can be allowed

我如何创建这种类型的表?
ID不能用于任何其他帐号,但可以用于同一帐号多次?
在此先感谢
Madhukumar N

[edit]代码块和数据的快速整理-OriginalGriff [/edit]

how can i create this type of table?
ID cannot be used for any Other Account Number but it can be used multiple times for same Account Number??
Thanks in advance
Madhukumar N

[edit]Code block and a quick tidy of the data - OriginalGriff[/edit]

推荐答案

如果要在服务器端执行此操作,可以使用触发器检查一下.请参见创建触发器 [
If you want to do this on server side, you can use a trigger to check this. See CREATE TRIGGER[^]

For example something like:
CREATE TRIGGER trg_MyTable FOR INSERT, UPDATE AS
BEGIN
   DECLARE @count int;
   SELECT @count = COUNT(*) FROM MyTable WHERE ... //insert the logic what row existences to check
   IF @count > 0 BEGIN
      RAISERROR(''Some error message'', 10, 1);
   END;
END;


您无法创建将自动强制执行此操作的表.

您必须手动创建规则,或者创建INSERT和UPDATE存储过程,或者在尝试创建/修改记录时在代码中执行规则.

SQL没有那种可用于自动记录验证的规则.

此外,您将需要一个记录ID行:您也不能对多个记录使用相同的ID.
You can''t create a table that will enforce this automatically.

You will have to apply the rules manually, either by creating INSERT and UPDATE stored procedures or by doing it in code when you try to create / modify the records.

SQL does not have those kind of rules available for automatic record validation.

In addition, you will need a record ID row: you cannot use the same ID for multiple records as well.


请参阅Frnd ID应该是唯一的,并且应该是主键.它绝对是数据库的标准
See Frnd Id should be Unique and it Should be a Primary key.Duplicate Id it sholud not be allowed It a Satandard of the Database


这篇关于具有唯一键的SQL表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆