Solved

sql alertative for in clause

Posted on 2012-04-12
16
400 Views
Last Modified: 2012-04-14
I have a table that has a column called categories.

in this column you can have 'women, shirts, dresses' or 'men, pants'

You get the idea...

Anyway, my question is when  user searches for men, if I do

select *
from items
where categories like '%men%'

it pulls back anything with men and women in it. because of the word "men"

how can I do something like ( my logic between [] )

select *
from items
where [categories has the whole exact word "men" in it.]

Thanks

Judson
0
Comment
Question by:judsonmusic
16 Comments
 
LVL 14

Expert Comment

by:Christopher Gordon
ID: 37839461
Maybe put in some additional spaces:
select *
from items
where categories like '% men %'
0
 
LVL 39

Accepted Solution

by:
Kyle Abrahams earned 500 total points
ID: 37839477
select *
from items
where 'men' in  (select replace(item, ' ', '') item from fn_txt_split(categories, ','))



/****** Object:  UserDefinedFunction [dbo].[fn_Txt_Split]    Script Date: 08/24/2010 09:10:21 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_Txt_Split]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_Txt_Split]
GO

/****** Object:  UserDefinedFunction [dbo].[fn_Txt_Split]    Script Date: 08/24/2010 09:10:21 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


Create Function [dbo].[fn_Txt_Split]( 
    @sInputList varchar(8000) -- List of delimited items 
  , @Delimiter char(1) = ',' -- delimiter that separates items 
) 
RETURNS @list table (Item varchar(8000)) 
as begin 
DECLARE @Item Varchar(8000) 
  
  

WHILE CHARINDEX(@Delimiter,@sInputList,0) <> 0 
BEGIN 
SELECT 
@Item=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@Delimiter,@sInputList,0 
)-1))), 
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@Delimiter,@sInputList,0)+1,LEN(@sInputList)))) 
  
IF LEN(@Item) > 0 
INSERT INTO @List SELECT @Item 
  
END 

  
IF LEN(@sInputList) > 0 
INSERT INTO @List SELECT @sInputList -- Put the last item in 
  
return 
END 

GO

Open in new window

0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 37839498
I originally thought of the spaces first, but if he's got 'pants, men, kids'

that becomes

' pants, men, kids '

and won't return properly.  The proper way is to split it into a table and then look within the table.
0
 
LVL 3

Author Comment

by:judsonmusic
ID: 37839506
ged325 can you explain furthur?
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 37839544
Judo:

I provided the answer in my previous post.

The function (in the code window) is a stand alone function which will split a string into a table.

(just copy and post the code into sql and execute).


You can then use that to split a delimitted string.

For instance

select * from fn_txt_split('1;2;3;4;5;',';')
returns
1
2
3
4
5

and
select * from fn_txt_split('a.b.c.d','.')
a
b
c
d



Since you have a comma delimited string, you can pass that to the function.  It will give you a table with 1 row per value.

Final query would look like:

select *
from items
where 'men' in  (select replace(item, ' ', '') item from fn_txt_split(categories, ','))



This doesn't handle your % search.  Do you still need to do that?
0
 
LVL 3

Author Comment

by:judsonmusic
ID: 37839562
select *
from items
where 'men' in  (select replace(item, ' ', '') item from fn_txt_split(categories, ','))

what is this doing? what is item???
0
 
LVL 3

Author Comment

by:judsonmusic
ID: 37839581
jsut to be clear, I have a link on a web page called "men" is passes a argument into a sql function in coldfusion which is like this(obviously this is not correct syntax below)

select *
from items
where [categories has the whole exact word "men" in it.]

so it will only pull back records like categories = 'men, shirts, pants' because that list has the word 'men' in it.
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 37839617
yep.  The the split will work.

item is coming from fn_txt_split

It is the only returning from that function.

I was just removing any spaces . . . I forget if the split trims for you automatically.

so in the case of
' men ,  pants'
it will still return the correct value.
0
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 
LVL 3

Author Comment

by:judsonmusic
ID: 37839753
so I run the function, then how would I pass all the values coming back from select * from items where category contains "mens"????

I dont think you have made it very clear on how to search each row for the category column.

Thanks

Judson
0
 
LVL 3

Author Comment

by:judsonmusic
ID: 37839778
actually your function works nicely! one problem though, how do I install this function on my hosting accounts server? or do I just run it each time in my <cfquery> tag

can you explain how that works? When you run it once, does it stay in the server indefinitely?

Thanks

Judson
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 37839813
The query to create the function is a 1 off run, as the function will be created in your database and then available for use until the database is dropped.
0
 
LVL 3

Author Comment

by:judsonmusic
ID: 37839926
Thats awesome. one small issue though. Some of my lists (categories) may have

'items for women, shirts, dresses, etc'

The way your function is now wont deal with that so I changed to this:

'women' in  (select item from fn_txt_split(replace(categories, ' ', ','), ','))

that way it will search all words :)

Thanks for your help!

Judson
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 37839965
Anytime.  Best of luck.
0
 
LVL 8

Expert Comment

by:tomvergote
ID: 37842418
The correct way would still be to normalize this out to a second table.
Using this replace or like function is guaranteed to be a performance wreck when you have enough items.

Also you mention there is a link on a site somewhere that fills in this parameter, so watch out for SQL injection.

If you ask me it's an accident waiting to happen.
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 37845434
like function is guaranteed to be a performance wreck when you have enough items.
Too true.  It is fine now with a few hundred rows, wait until you have 100K rows and I suspect we will see you here again.

If you ask me it's an accident waiting to happen.
But, it is also an invaluable learning lesson.
0
 
LVL 3

Author Comment

by:judsonmusic
ID: 37846250
In coldfusion I am using a local component/ method which only allows specific arguments enclosed in cfquery param tags to avoid SQL injection attacks. I am not using likes. I am using that wonderful split function. The site is in progress but it's www.feelthevibration.com beware its an adult novelty website ;) but I  a web developer and it's been a fun project!

It's best  viewed in safari or chrome to get the 3d effect!

Judson
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now