Solved

CHARINDEX Chooses wrong result

Posted on 2011-03-21
3
379 Views
Last Modified: 2012-06-21
CHARINDEX works most of the time very well, but sometimes it chooses the wrong id. ID is an integer while the search string is varchar      

DECLARE @MyId AS VARCHAR (500)
      SET @MyId = '7,17,107,177'
      
SELECT * FROM leads.BatchDetails
WHERE
  (@MyId IS NULL OR @MyId = '' OR
             CHARINDEX(CAST(Id AS VARCHAR),@MyId)>0)

This will select from the DB '10' because it finds it in '107'
7
10
17
107
177

The problem is id 10


0
Comment
Question by:Internet_Engineer
  • 2
3 Comments
 
LVL 3

Accepted Solution

by:
ssisworo earned 500 total points
ID: 35182697
try this :
and always add ',' at end of @MyId

---------------------
DECLARE @MyId AS VARCHAR (500)
      SET @MyId = '7,17,107,177,'
     
SELECT CHARINDEX(cast(Id as varchar), @MyId ), * FROM Person
WHERE
  @MyId IS NULL OR @MyId = '' OR
             ( CHARINDEX(cast(Id as varchar), @MyId )>0 and
               substring(@MyId,CHARINDEX(cast(Id as varchar), @MyId ) + len(cast(Id as varchar)),1) = ',')

--------------------
0
 
LVL 3

Expert Comment

by:ssisworo
ID: 35182781

DECLARE @MyId AS VARCHAR (500)
      SET @MyId = '7,17,107,177,'
     
SELECT * FROM Personleads.BatchDetails
WHERE
  @MyId IS NULL OR @MyId = '' OR
             ( CHARINDEX(cast(Id as varchar), @MyId )>0 and
               substring(@MyId,CHARINDEX(cast(Id as varchar), @MyId ) + len(cast(Id as varchar)),1) = ',')
0
 

Author Closing Comment

by:Internet_Engineer
ID: 35182829
It works
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

743 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

10 Experts available now in Live!

Get 1:1 Help Now