The main problem you have is testing for the Column = '' rather than the variable as Zoltan has pointed out, but you're also not catering for null values.
The following solution will cater for any of the columns being null AND/OR any of the variables being null
DECLARE @MRN VARCHAR(3)
DECLARE @FN varchar(30)
DECLARE @LN varchar(30)
DECLARE @DOB Date
SET @MRN = ''
SET @FN = NULL
SET @LN = 'Smith'
SET @DOB = NULL
SELECT [Last_Name],[First_Name], [middle_name],[Patient_No],[gender],[Date_of_Birth]
FROM [Demographics]
where
ISNULL([Patient_No],'') LIKE COALESCE(@MRN + '%',Patient_No,'%')
AND
ISNULL([Last_Name],'') LIKE COALESCE(@LN + '%', Last_Name, '%')
AND
ISNULL([First_Name],'') LIKE COALESCE(@FN + '%', First_Name, '%')
AND
ISNULL(Date_of_Birth,'14-OCT-1066') = COALESCE(@DOB, Date_of_Birth, '14-OCT-1066')
A couple of points of interest:
- I used 14-OCT-1066 for handling null dates of birth, largely because no-one is likely to have that date of birth - you might need to change this depending on your context. (Aside - it's the date of the Battle of Hastings if you're interested)
- I used
LIKE
for the Patient_No instead of
=
to simplify the code - i.e. to avoid having to use a case statement. Otherwise that first condition would have been
ISNULL([Patient_No],'') = CASE WHEN @MRN='' THEN ISNULL(Patient_No,'') ELSE COALESCE(@MRN,Patient_No,'') END