如何约束不能插入相同的记录?

normandj 2008-07-21 09:21:43
表A字段:

编号,姓名,年份,备注
编号为主键

如何做到 姓名=姓名, 年份=年份 时不让插入记录?

我记得触发器可能,除此外还有什么文法。
...全文
130 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
win7cc 2008-07-21
  • 打赏
  • 举报
回复
create table ta (id int,name char(5),unique(name),unique(id))

insert into ta select '2','abc'
insert into ta select '1','abc'


(所影响的行数为 1 行)

服务器: 消息 2627,级别 14,状态 2,行 1
违反了 UNIQUE KEY 约束 'UQ__ta__263B8EAF'。不能在对象 'ta' 中插入重复键。
语句已终止。
lgxyz 2008-07-21
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 wgzaaa 的回复:]
1、2楼均可,还可用check约束
create table tt_a(a int,b varchar(10))
insert tt_a select 1,'a'
-----------------------先建一函数
create function fun_un(@a int,@b varchar(10))returns int as
begin
declare @out int
set @out=1
if exists(select 0 from tt_a where a=@a and b=@b group by a,b having count(*)>1)
set @out=0
return @out
end
----------------------给表加check约束
alter …
[/Quote]
hyde100 2008-07-21
  • 打赏
  • 举报
回复
在表中姓名,年份上建立UNIQUE KEY
tangserver 2008-07-21
  • 打赏
  • 举报
回复
用except可以么?
wgzaaa 2008-07-21
  • 打赏
  • 举报
回复
1、2楼均可,还可用check约束
create table tt_a(a int,b varchar(10))
insert tt_a select 1,'a'
-----------------------先建一函数
create function fun_un(@a int,@b varchar(10))returns int as
begin
declare @out int
set @out=1
if exists(select 0 from tt_a where a=@a and b=@b group by a,b having count(*)>1)
set @out=0
return @out
end
----------------------给表加check约束
alter table tt_a add check(dbo.fun_un(a,b)=1)
insert tt_a select 1,'d'
insert tt_a select 1,'a'
----------------------------

(所影响的行数为 1 行)

服务器: 消息 547,级别 16,状态 1,行 1
INSERT 语句与 TABLE CHECK 约束 'CK__tt_a__54CB950F' 冲突。该冲突发生于数据库 'weixiu2',表 'tt_a'。
语句已终止。
bwu851 2008-07-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wzy_love_sly 的回复:]
unique和primary key
[/Quote]

wwd252 2008-07-21
  • 打赏
  • 举报
回复
在程序中判断
ojuju10 2008-07-21
  • 打赏
  • 举报
回复

用约束,如果违反约束时会报错

最好在程序插入前判断
wzy_love_sly 2008-07-21
  • 打赏
  • 举报
回复
create table ta(id int,name varchar(50) unique(id,name))
create table tb(id int,name varchar(50) primary key(id,name))

insert into ta select 1,'a'
insert into ta select 1,'a'

insert into tb select 1,'a'
insert into tb select 1,'a'


(1 行受影响)
消息 2627,级别 14,状态 1,第 5 行
违反了 UNIQUE KEY 约束 'UQ__ta__20238DFD'。不能在对象 'dbo.ta' 中插入重复键。
语句已终止。

(1 行受影响)
消息 2627,级别 14,状态 1,第 8 行
违反了 PRIMARY KEY 约束 'PK__tb__220BD66F'。不能在对象 'dbo.tb' 中插入重复键。
ojuju10 2008-07-21
  • 打赏
  • 举报
回复
插入前用程序判断!
wzy_love_sly 2008-07-21
  • 打赏
  • 举报
回复
unique和primary key

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧