Question

Im trying to write a report using an sql query

      SELECT 
r.PostCode,
r.Email
FROM dbo.tbl_RegisterMain_Holding as r
Where r.PostCode LIKE @PostCode AND RegisterType = '2'

When the report is run you can put in multiple postcodes to search by, however i don't get any results back.

I only want to search by the first 3 or 4 letters of the post code. Any Idea why this is not bringing back data? Would be much appreciated Thanks

Was it helpful?

Solution

If @PostCode contains a SINGLE postcode/fragment to search for, and assuming you want to search for matches STARTING with that value, try:

Where r.PostCode LIKE @PostCode + '%' AND RegisterType = '2'

If @PostCode contains MULTIPLE postcodes/fragments to search for (e.g. "AB,AC,AD") then this approach will not work and you need a way to split them out into the individual values first before matching. You can use one of the approaches I've outlined here, except the JOIN would use a LIKE instead of an equals.

Edit:

As they are comma separated, then you need to go down one of the routes outlined in the link above. There's 3 options available for passing the multiple values in : CSV (as you are), XML or Table Valued Parameter. Table Valued Parameter is IMHO the best route to go down. But assuming you stick with CSV, the end SQL would be (needs the fnSplit function):

SELECT r.PostCode, r.Email
FROM dbo.tbl_RegisterMain_Holding as r
    JOIN dbo.fnSplit(@Postcode, ',') t ON r.PostCode LIKE t.Item + '%'

OTHER TIPS

LIKE operator searches for a pattern. So, you must add wildcards to your var @PostalCode.

Try:

SELECT r.PostCode, r.Email FROM dbo.tbl_RegisterMain_Holding as r
WHERE r.PostCode LIKE '%' + @PostCode + '%' AND RegisterType = '2'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top