我建立一張表,包括a、b、c、d、e五個字段。a只能選擇0和1,如果a=1,則要求b+C+D三個字段是唯一的,如果在DDL方面進行控制。
下面的代碼親測可用的了……
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TestAsk]') AND type in (N'U'))
DROP TABLE [dbo].[TestAsk]
GO
CREATE TABLE [dbo].[TestAsk](
[id] int primary key identity(1,1), --主鍵
[a] bit NOT NULL,
[b] [varchar](50),
[c] [varchar](50),
[d] [varchar](50),
[e] [varchar](50)
) ON [PRIMARY]
GO
-- =============================================
-- Author: yenange
-- Create date: 2014-12-27
-- Description: a=1時,b,c,d必須唯一
-- =============================================
CREATE TRIGGER [dbo].[trig_TestAsk_I_U]
ON [dbo].[TestAsk]
FOR INSERT, UPDATE
AS
BEGIN
--如果插入(修改)的記錄中存在:
--1. a=1
--2. 與原表相比:b,c,d相同, 但主鍵不同
--則拋出錯誤信息
IF EXISTS (SELECT 1 FROM [TestAsk] T1 where exists(
select 1 from INSERTED T2 where T2.a=1 and T1.b=T2.b and T1.c=T2.c and T1.d=T2.d and T1.id!=T2.id
) )
begin
raiserror ('a=1時,b,c,d必須唯一!',16,1)
rollback tran;
end
END
go
--測試
--1. a=0時
insert into [TestAsk] (a,b,c,d) values(0,'b', 'c', 'd')
insert into [TestAsk] (a,b,c,d) values(0,'b', 'c', 'd')
insert into [TestAsk] (a,b,c,d) values(0,'b', 'c', 'e')
select *, 'a=0 insert後' as op from TestAsk
update TestAsk set d='d' where id=3
select *, 'a=0 update後' as op from TestAsk
--2. a=1
insert into [TestAsk] (a,b,c,d) values(1,'b', 'c', 'd')
go
update TestAsk set a=1 where id=3
go
select *, 'a=1 insert,update後' as op from TestAsk