Code
Create TRIGGER [dbo].[nameTrigger]
ON [dbo].[Student]
for INSERT,UPDATE
AS
BEGIN
declare @InsertedName varchar(50)
declare @Count int
declare @StudentId int
set @InsertedName=(select [Name] from Inserted)
set @StudentId=(select [StudentId] from Inserted)
set @Count=(select count(*)
from Student
where [Name]= @InsertedName and StudentId <> @StudentId)
if @Count > 0
begin
RaisError('数据库中有同名,插入或更新失败',16,1)
rollBack Tran
end
END
Create TRIGGER [dbo].[nameTrigger]
ON [dbo].[Student]
for INSERT,UPDATE
AS
BEGIN
declare @InsertedName varchar(50)
declare @Count int
declare @StudentId int
set @InsertedName=(select [Name] from Inserted)
set @StudentId=(select [StudentId] from Inserted)
set @Count=(select count(*)
from Student
where [Name]= @InsertedName and StudentId <> @StudentId)
if @Count > 0
begin
RaisError('数据库中有同名,插入或更新失败',16,1)
rollBack Tran
end
END
Student表如下,其中Name列可以为null,但是,不是null列不能有重复!也就是说可以没有名字,但是不能有重名情况!
Code
CREATE TABLE [dbo].[Student](
[StudentId] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Age] [int] NULL,
[ClassId] [int] NULL,
)
CREATE TABLE [dbo].[Student](
[StudentId] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Age] [int] NULL,
[ClassId] [int] NULL,
)