Skip to main content

How to Query Comma Separated Value Column in SQL

Introduction

This is a small SQL function which will be useful for querying a Table which is having a comma separated value column.

Background

Sometimes, you encounter a column that stores comma separated values. This solution makes it easy to search such a column. However, it is recommended, if possible, to split the tables into two according to the First Normal Form.
For example: Storing the days of week in CSV format [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Sunday], for months in numbers [1,2,3,4,5,6,7,8,9,10,11,12]
I came across this requirement for storing the days in CSV format as reminder follow up for the user, and to query it.

Problem

Sometimes, we used to store a comma separated value in a column and which we will be using for some purpose in order to avoid creating a new table for that functionality. In this case, equals = search or contains Search or Like query will not work as expected to find one or more item present in the comma separated value Column, Inorder to overcome the problem I have created this function for querying the column in multiple scenarios which the developer can use according to his/her need.

Using the Code

First, we have to create a User Defined Function, which will take the comma separated value as the input and returns the items in a table format.
 create function dbo.fun_CSVtoTable(
 @csv nvarchar (4000),
 @Delimiter nvarchar (10)
 )
returns @returnValue table ([Item] nvarchar(4000))
begin
 declare @NextValue nvarchar(4000)
 declare @Position int
 declare @NextPosition int
 declare @comma nvarchar(1) 
 set @NextValue = ''
 set @comma = right(@csv,1)  
 set @csv = @csv + @Delimiter 
 set @Position = charindex(@Delimiter,@csv)
 set @NextPosition = 1 
 while (@Position <>  0)  
 begin
  set @NextValue = substring(@csv,1,@Position - 1) 
  insert into @returnValue ( [Item]) Values (@NextValue) 
  set @csv = substring(@csv,@Position +1,len(@csv))  
  set @NextPosition = @Position
  set @Position  = charindex(@Delimiter,@csv)
 end 
 return
end
The below User Defined Function is used for querying the items in CSV column under different scenarios such as Contains Search, Exact Match Search, Exact Contains Search.
create function dbo.fun_QueryCSVColumn(
 @csvColumn nvarchar (4000),
 @Delimiter nvarchar (2),
 @value nvarchar(4000),
 @search nvarchar(50) -- 'contains' | 'exact contains' | 'exact match'
 )
returns   nvarchar(1)
begin
declare @return varchar(1) = '0'
declare @table_ColumnValue table (value nvarchar(100))
declare @table_InputValue table (value nvarchar(100))
declare @joinCount int
declare @valuecount int
declare @Columnvaluecount int
insert into @table_ColumnValue  select distinct item from dbo.fun_CSVtoTable(@csvColumn,@Delimiter)
insert into @table_InputValue  select distinct item  from dbo.fun_CSVtoTable(@value,@Delimiter)
 select @joinCount =  count(*) from @table_ColumnValue a inner join _
     @table_InputValue b on a.value = b.value
 select @valuecount = count(*) from @table_InputValue
 select @Columnvaluecount = count(*) from @table_ColumnValue
 if(@search = 'contains') begin
 if @joinCount >0
 set @return = '1'  
 end
 else if (@search = 'exact contains')
 begin   
 if(@joinCount = @valuecount)
 set @return = '1' 
 end
else if (@search = 'exact match')
begin
 if( @joinCount = @valuecount and @joinCount= @Columnvaluecount )
 set @return ='1'
end 
 return @return
 
end
After the above function is created, we can use the below queries to Search the item(s) in the CSV column.
I have used the below table for demo purposes.
CSVColumn
a,b
a,b,c
a
b
c
a,c
Querying the above column in 3 different scenarios:

Contains

select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','a','contains')
CSVColumn
a,b
a,b,c
a
a,c
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','b,a','contains')
CSVColumn
a,b
a,b,c
a
b
a,c

Exact Contains

select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','b,a','exact contains')
CSVColumn
a,b
a,b,c
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','c,b','exact contains')
CSVColumn
a,b,c

Exact Match

select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','a,b,c','exact match') 
CSVColumn
a,b,c
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','b,a','exact match')
CSVColumn
a,b

Points of Interest

But one thing you should keep in mind is, this will reduce the performance of the select query since we are using User defined function in select statement, we should use this only when the CSV items are very few and the rows length is considerable range.
Before creating a CSV column, just read about Database Normalisation.
I have used Comma in the example, you shall use any char as delimiter, it depends upon how you are storing the values in the table.

History

  • Initial version


Ref : https://www.codeproject.com/Tips/1101816/How-to-Query-Comma-Seperated-Value-Column-in-SQL

Comments

Popular posts from this blog

Tip/Trick: Fix Common SEO Problems Using the URL Rewrite Extension

Search engine optimization (SEO) is important for any publically facing web-site.  A large % of traffic to sites now comes directly from search engines, and improving your site’s search relevancy will lead to more users visiting your site from search engine queries.  This can directly or indirectly increase the money you make through your site. This blog post covers how you can use the free Microsoft  URL Rewrite Extension  to fix a bunch of common SEO problems that your site might have.  It takes less than 15 minutes (and no code changes) to apply 4 simple  URL Rewrite  rules to your site, and in doing so cause search engines to drive more visitors and traffic to your site.  The techniques below work equally well with both ASP.NET Web Forms and ASP.NET MVC based sites.  They also works with all versions of ASP.NET (and even work with non-ASP.NET content). [In addition to blogging, I am also now using Twitter for quick updates and to sh...

ASP.NET MVC - Set custom IIdentity or IPrincipal

Here's how I do it. I decided to use IPrincipal instead of IIdentity because it means I don't have to implement both IIdentity and IPrincipal. Create the interface interface ICustomPrincipal : IPrincipal { int UserId { get ; set ; } string FirstName { get ; set ; } string LastName { get ; set ; } } CustomPrincipal public class CustomPrincipal : ICustomPrincipal { public IIdentity Identity { get ; private set ; } public bool IsInRole ( string role ) { return false ; } public CustomPrincipal ( string email ) { this . Identity = new GenericIdentity ( email ); } public int UserId { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } CustomPrincipalSerializeModel - for serializing custom information into userdata field in FormsAuthenticationTicket object. public class CustomPrincipalSerializeMode...

linq orderby multiple columns dynamically

So, it's been a while, but I thought I take moment and do my annual blog post ;). I've been playing around with  ASP.NET MVC  and the Linq stuff for  NHibernate  recently. I was in need of an OrderBy extension method that could take a SQL-Like OrderBy string and sort a IQueryable<> or IEnumerable<> collection. I wrote up an implementation that worked, but I just wasn't satisfied with its internals (quite a bit of reflection to get the correct type to construct a LambdaExpression, etc) At any rate, I couldn't leave well enough alone, and, after a bit of Googling, I ran across this  StackOverflow  answer about Dynamic LINQ OrderBy . The extension method wasn't exactly what I was looking for, but that ApplyOrder method is slick, and solved the portion of my implementation that was bothering me. So, I though I would post up my version in case anybody finds it useful. It handles the following inputs: list.OrderBy( "SomeProperty" ); list.Ord...