Check if record Exists in Database in SQL Server

Last Reply 3 months ago By pandeyism

Posted 3 months ago

I have a database table for example name is tabcustomer  

what i want to check by query is If there already exists

IDCustomerFather = A

IDCustomerSon = B 

If anybody  trying to insert

IDCustomerFather = B

IDCustomerSon = A 

i want to stop this kind of insert

 

 

You are viewing reply posted by: pandeyism 3 months ago.
Posted 3 months ago

Hey rakibxl,

Please refer below sample.

SQL

DECLARE @FatherSonRelation AS TABLE(IDCustomerFather VARCHAR(10), IDCustomerSon VARCHAR(10))
INSERT INTO @FatherSonRelation VALUES('A','B')
DECLARE @Father VARCHAR(10)
DECLARE @Son VARCHAR(10)
SET @Father='B'
SET @Son='A'

IF EXISTS(SELECT * FROM @FatherSonRelation WHERE (IDCustomerFather=@Father AND IDCustomerSon=@son) OR (IDCustomerFather=@Son AND IDCustomerSon=@Father))
BEGIN
	PRINT 'You Can not insert'
END
ELSE	
BEGIN
	INSERT INTO @FatherSonRelation VALUES(@Father, @Son)
	SELECT * FROM @FatherSonRelation
END