Question about SQL restrictions

In Sql Server 2005, I have a table with two whole columns, name them Id1 and Id2. I need them to be unique in the table (simple enough with a unique index that spans both columns). I also need them to be unique in the table if the values ​​are transposed between two columns.

For example, SELECT * FROM MyTable returns

Id1   Id2
---------
2     4
5     8
7     2
4     2  <--- values transposed from the first row

How to create a constraint that will prevent the last row from being entered into the table, since they are transposed values ​​from the first row?

+3
source share
3 answers

, , , .

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)
+6

Id1 Id2 ? , , Id1 < Id2 . , .

+2

, , select, . , , , .

0
source

Source: https://habr.com/ru/post/1704528/


All Articles