Select specific column based on another column value in SQL Server

Last Reply 5 months ago By pandeyism

Posted 5 months ago

Please help how can i construct this logic

select Fatherphone,MotherPhone,FFromdate,FTos,Mfrom,Mdate  from  students 

 

Now 

i wanted to have like if the Fathercontact=0782911364 then

select  Fatherphone ,FFromdate,FTos from students 

i wanted to have like if the Mothercontact=0782911364 then

select  MotherPhone ,Mfrom,Mdate from students 

 

 

 

Posted 5 months ago Modified on 5 months ago

Hey makumbi,

Please refer below sample query

SQL

DECLARE @TestDemo AS TABLE(Fatherphone VARCHAR(20),MotherPhone VARCHAR(20),FFromdate VARCHAR(20),FTos VARCHAR(20),Mfrom VARCHAR(20),Mdate VARCHAR(20))
INSERT INTO @TestDemo VALUES('0782911364','0782911364','01-02-2017','02-02-2017','03-02-2018','02-02-2018')
INSERT INTO @TestDemo VALUES('0782911363','0782911363','01-02-2017','02-02-2017','03-02-2018','02-02-2018')

DECLARE @phone VARCHAR(20)
SET @phone='0782911363'
IF EXISTS(SELECT * FROM @TestDemo
          WHERE Fatherphone = @phone)
BEGIN
		SELECT Fatherphone,FFromdate,FTos FROM @TestDemo
		WHERE Fatherphone = @phone
END
ELSE
BEGIN
		SELECT MotherPhone,Mfrom,Mdate FROM @TestDemo
		WHERE MotherPhone = @phone
END

Output

Fatherphone FFromdate FTos
782911363 1/2/2017 2/2/2017