在Sql Server 2005中,我有一个包含两个整数列的表,称为Id1和Id2.我需要它们在表中是唯一的(使用跨越两列的唯一索引很容易).如果值在两列之间转换,我还需要它们在表中是唯一的.
例如,SELECT*FROM MyTable返回
Id1 Id2
---------
2 4
5 8
7 2
4 2 <--- values transposed from the first row
Run Code Online (Sandbox Code Playgroud)
如何制作一个约束来阻止最后一行输入到表中,因为它们是第一行的转置值?
创建一个检查约束,该约束绑定到用户定义的函数,该函数对表执行select以检查转置值.
Create table mytable(id1 int, id2 int)
go
create Function dbo.fx_Transposed(@id1 int, @id2 int)
returns bit as
Begin
Declare @Ret bit
Set @ret = 0
if exists(Select 1 from MyTable
Where id2 = @id1 and id1 = @id2)
Set @ret = 1
Return @ret
End
GO
Alter table mytable add
CONSTRAINT [CHK_TRANSPOSE] CHECK
(([dbo].[fx_Transposed]([ID1],[ID2])=(0)))
GO
Insert into mytable (id1, id2) values (1,2)
Insert into mytable (id1, id2) values (2,1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
232 次 |
| 最近记录: |