1

I am using SQL Server to search through multiple columns (over 20 in reality) in my table containing part of a certain value, but I keep getting the error

'CONCAT' is not a recognized built-in function name

I am running SQL Server 2017 and the function should be available, so I'm not sure if there's an error in my query or if something else is causing the error.

SELECT *
FROM table 
WHERE 
   CONCAT(col1, col2, col3, col4, col5, col6, col7, col8) LIKE '%val%'

Thank you in advance

11
  • Sample data would be nice. Commented Dec 17, 2018 at 15:16
  • 1
    Are you sure you want your select to return data when e.g. col1 = 'v', col2='a' and col3 = 'l' ? Commented Dec 17, 2018 at 15:17
  • 2
    Note that 'somewhere' || 'wolfenstein' like '%wherewolf%' returns true. Commented Dec 17, 2018 at 15:17
  • 1
    Exactly my point earlier. I love the joke though :) Commented Dec 17, 2018 at 15:18
  • try stackoverflow.com/questions/50504757/… Commented Dec 17, 2018 at 15:20

3 Answers 3

4

Use +:

where (col1 + col2 + col3 + col4 + col5 + col6 + col7 + col8) like '%val%'

This assumes that all the columns are non-NULL string columns.

If they could be NULL or are not strings, then you need explicit conversion:

where (coalesce(convert(nvarchar(max), col1), '') +
       coalesce(convert(nvarchar(max), col2), '') +
       . . .
       coalesce(convert(varchar(max), col8), '') +
      ) like '%val%'
Sign up to request clarification or add additional context in comments.

Comments

3

I'd tweak Gordon's solution slightly to insert some delimiting character between the concatenated terms to avoid scenarios where the end of the one value and the start of the next combine to give you a match.

where (col1 + '|' + col2 + '|' + col3 + '|' + col4 + '|' + col5 + '|' + col6 + '|' + col7 + '|' + col8) like '%val%'

1 Comment

Seems like this should really be a comment on Gordon's answer to me. Also, I never use single character delimiters (could be part of the data); I choose something more like '[DELIM]'.
3

Just another option, however I suspect concat() or Gordon's (+1) would be more performant

Select *
 From  YourTable A
 Where (select A.* for xml raw) like '%YourSearch%'

EDIT

Just for fun, I ran a comparison of the the concat() vs the xml approach. The sample was 25K rows with 101 columns. The average of 5 runs for concat was 886ms while the xml was 1.162.

Clearly concat() is the winner, but the xml approach was not horrible, and may be another option in a discovery phase.

Comments

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.