34,590
社区成员
发帖
与我相关
我的任务
分享
select * from sys.key_constraints where type='pk'
--定义一个表
declare @student table
(id int primary key ,[name] varchar(20),[name1] float)
--插入一条数据
insert into @student
select 1,'a',2.45
--查看一下
select * from @student
/*
id name name1
----------- -------------------- ----------------------
1 a 2.45
*/
--再插入一个相同的id
insert into @student
select 1,'b',3.45
/*提示:
Violation of PRIMARY KEY constraint 'PK__#6C040022__6CF8245B'.
Cannot insert duplicate key in object 'dbo.@student'
*/
create table student(
ID int not null identity(1,1) primary key,
Name nvarchar(20),
......
)
--一般来说是设置自增列,如果你想判断插入,可以用触发器来控制,或者直接在程序里写方法控制!
create trigger t_in on tb
for insert
as
insert into tb
select *
from inserted t
where not exists (select 1 from tb where id = t.id)
--建议做自增列!