How to use LIKE and CONCAT() with variable in T-SQL

Viewed 2894

I am working on a query using T-SQL.

Goal: return rows that contain a name stored in a variable.

My issue: the query returns all rows, without filtering.

Additional info: The names are stored as varchar and there are several spaces after the letters which is why I want to concatenate the variable with '%'.

Also, when I ran the query with just one '%' appended on the end of the variable, the database returned all records beginning with 'D'.

My query:

DECLARE @fName as varchar;
SET @fName='DILLON';

SELECT DISTINCT 
    e.FIRST_NAME, e.LAST_NAME, e.EMAIL_ADDRESS
FROM 
    [172.20.11.11].LSLMDB.dbo.vwEmployee e
JOIN 
    [172.20.11.11].LSLMDB.ls_apps.PAEMPLOYEE pa ON pa.EMPLOYEE = e.EMPLOYEE
JOIN
    [172.20.11.11].LSLMDB.ls_apps.PCODES pc ON pa.LOCAT_CODE = pc.CODE
JOIN
    [172.20.11.11].LSLMDB.ls_apps.PCODESDTL pcd ON pc.CODE = pcd.CODE 
WHERE 
    e.FIRST_NAME LIKE CONCAT('%',@fName,'%');

I appreciate any attempts to help!

1 Answers
Related