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

C# Generic class to parse value - "GenericConverter"

    public class GenericConverter     {         public static T Parse<T>(string sourceValue) where T : IConvertible         {             return (T)Convert.ChangeType(sourceValue, typeof(T));         }         public static T Parse<T>(string sourceValue, IFormatProvider provider) where T : IConvertible         {             return (T)Convert.ChangeType(sourceValue, typeof(T), provider);         }     }     public static class TConverter     {         public static T ChangeType<T>(object value)         {             return (T)ChangeType(typeof(T), value);         }         public static object ChangeType(Type t, object value)         {             TypeConverter tc = TypeDescriptor.GetConverter(t);             return tc.ConvertFrom(value);         }         public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter         {             TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));         }     } ----------------

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 share links. Follow me at:  twitter.com/scottg

How to create a countdown timer in jquery

Create a countdown timer in jQuery First we need to include the jQuery library file to the HTML page to perform this task. To do that we need to understand that what exactly a jQuery library fie is ? JQuery library file is the library of JavaScript, which means this file contains the predefined functions of jQuery. We just need to call these functions to perform the task. jQuery functions reduces the lines of code and makes our task easy. As this jQuery library file contains the javascript functions so we need to call the function within <script> </script> tag. Now after including the file, we need to define a variable which will store that for how long you want the timer on the page(c=60) and now the time you set needs to be changed in hours , minutes and seconds using the code “ var hours = parseInt( time / 3600 ) % ;var minutes = parseInt( time / 60 ) % 60; var seconds = time % 60;” Now we need to put the condition if timer got finished (if (t