?
Solved

sql alertative for in clause

Posted on 2012-04-12
16
Medium Priority
?
414 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 40

Accepted Solution

by:
Kyle Abrahams earned 2000 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 40

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
Get MongoDB database support online, now!

At Percona’s web store you can order your MongoDB database support needs in minutes. No hassles, no fuss, just pick and click. Pay online with a credit card. Handle your MongoDB database support now!

 
LVL 3

Author Comment

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

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 40

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
 
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 40

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 40

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Suggested Courses

801 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