Çoklu null değerleri kabul eden Unique constraitler(Allow multi nulls unique)

Merhaba arkadaşlar;

Unique kısıtlaması Oracle da oldu gibi birden fazla null değeri kabul etmezler. Bunun için şöyle bir çözüm yolu geliştirebilir. Hesaplanmış bir alanı böyle bir kısıtlamaya gidereek istediğimiz amaca ulaşırız. Bu alan asıl alanı kontrol etsin, null ise id değeri alsın, tersi durumdaa asıl alanı alsın.

USE [master]
GO
Create Database [Dukkan]
go
use [Dukkan]
go

Create Table Urun
([id] int not NULL constraint id primary key clustered,
[Barcode]  int NULL)
go

--Burada hesaplanmış alan oluşturalım
Alter table Urun Add bcd as case when [Barcode]
 is NULL then [id] else [Barcode] end
go
Alter table Urun Add constraint bcd_unique UNIQUE ([bcd] )
go
Insert into Urun([id],[Barcode])
values(1,31423)
go
Insert into Urun([id],[Barcode])
values(2,null)
go
Insert into Urun([id],[Barcode])
values(3,null)
go

Eğer Barcode alanı varchar(20) gibi bir değer olacak ise hesaplanmı alanda convert etmek gerekecektir... Kodu tekrar düzenlersek aşağıdaki gibi yazman gerekir..

USE [master]
GO
Create Database [Dukkan]
go
use [Dukkan]
go

Create Table Urun
([id] int not NULL constraint id primary key clustered,
[Barcode]  varchar(20) NULL)
go

--Burada hesaplanmış alan oluşturalım
Alter table Urun Add bcd as case when [Barcode]
 is NULL then convert(varchar(20),[id]) else [Barcode] end
go
Alter table Urun Add constraint bcd_unique UNIQUE ([bcd] )
go
Insert into Urun([id],[Barcode])
values(1,'31423123123123')
go
Insert into Urun([id],[Barcode])
values(2,null)
go
Insert into Urun([id],[Barcode])
values(3,null)
go

 

Bir sonraki ipucunda görüşmek üzere hoşçakalın..

Add comment

The file '/Custom/Widgets/Calendar/widget.cshtml' does not exist.The file '/Custom/Widgets/Category list/widget.cshtml' does not exist.The file '/Custom/Widgets/Tag cloud/widget.cshtml' does not exist.The file '/Custom/Widgets/Page List/widget.cshtml' does not exist.The file '/Custom/Widgets/Month List/widget.cshtml' does not exist.