Quantcast
Viewing all articles
Browse latest Browse all 2

Search in a string field

I would use a Numbers table for this:

declare @t table (parentkey int, expression varchar(100))
insert @t select 1,'if col1=''234'' and col2=''abc'' or col1=''456'' and col2=''bb'' else if col1=''78'''
union all select 2,'if colx=''987'' and colz=''12'''

select parentkey,columnname,colvalue
from @t
join Numbers on substring(expression,N,1)='=' and N<len(expression)
cross apply (select leftpart=' '+substring(expression,1,N-1)
                   ,rightpart=substring(expression,N+1,len(expression))+' ') F1
cross apply (select p1=len(leftpart)-charindex(' ',reverse(leftpart))+1
                   ,p2=charindex(' ',rightpart)) F2
cross apply (select columnname=substring(leftpart,p1+1,len(leftpart))
                   ,colvalue=left(rightpart,p2-1)) F3
/*
 parentkey columnname  colvalue
---------- ----------- --------
         1 col1        '234'
         1 col2        'abc'
         1 col1        '456'
         1 col2        'bb'
         1 col1        '78'
         2 colx        '987'
         2 colz        '12'
*/


Here is the code to build a permanent table of numbers (from 1 to 1million in your database:

create table Numbers (N int primary key);
go
with 
   L0 as (select 1 as C union all select 1)       --2 rows
  ,L1 as (select 1 as C from L0 as A, L0 as B)    --4 rows (2x2)
  ,L2 as (select 1 as C from L1 as A, L1 as B)    --16 rows (4x4)
  ,L3 as (select 1 as C from L2 as A, L2 as B)    --256 rows (16x16)
  ,L4 as (select 1 as C from L3 as A, L3 as B)    --65536 rows (256x256)
  ,L5 as (select 1 as C from L4 as A, L4 as B)    --4,294,967,296 rows (65536x65536)
  ,Nums as (select row_number() over (order by (select 0)) as N from L5)  
insert Numbers
select N from Nums
where N<=1000000;





--Brad (My Blog)

Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>