2

I need to perform a search in a SQL Server comma string.

For example :

The column type has values "A, C, T" and the user passes through an app the values "M, T".

I need to return all rows containing at least M, T, or both. In this case, A, C, T must be returned.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 8
    Don't store data as comma separated items. It will only cause you lots of trouble. – jarlh Sep 09 '16 at 09:30
  • 1
    Split your value first (http://stackoverflow.com/questions/10581772/how-to-split-a-comma-separated-value-to-columns) and then compare it – Prisoner Sep 09 '16 at 09:32

1 Answers1

1

The correct solution is to fix your data structure, with one type per row. You should not be storing multiple values in a single column.

But, sometimes we are stuck with other people's bad design decisions. You can use like to solve this:

where ', ' + type + ', ' like '%, M, %' or
      ', ' + type + ', ' like '%, T, %'

The trick here is to wrap commas round type, so that 'M' and 'T' will also be found when they are the start or end of type.

Jan Doggen
  • 8,799
  • 13
  • 70
  • 144
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786