6

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!

4
  • 4
    Always, always declare your varchar variables with an explicit length. Lest you end up with one that's unexpectedly only one character long, like you're running into now. It's a bad habit to kick. Commented Aug 3, 2017 at 16:45
  • Thanks for the advice! Commented Aug 3, 2017 at 16:52
  • While the solution was fairly simple to solve, this question was very well asked... thanks for putting in the effort and welcome to SO Dillion. Commented Aug 3, 2017 at 16:53
  • Thanks, I'm glad to see the community is quite responsive. Commented Aug 3, 2017 at 17:00

1 Answer 1

8

The problem is the system is defaulting to DECLARE @fName as varchar(1) -- this is probably not what you want. Change to DECLARE @fName as varchar(100); This should work as expected.

the query returns all rows, without filtering.

No it is returning all rows that contain D. Depending on coallation settings this might include both upper and lower case matches

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

Since it was just a single character the filter became D% which would return all records starting with D.

Sign up to request clarification or add additional context in comments.

2 Comments

Sweet, thanks! Overlooked that... My rep won't let the vote change publicly, just so you know.
@DillonHarless -- I think you just have to wait for a few minutes before you can vote at your level. Good Luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.