0

I am using SQL query shown below to compare AMCcode. But if I compare the AMCcode '1' using LIKE operator it will compare all the entries with AMCcode 1, 10,11,12,13. .. 19, 21,31.... etc. But I want to match the AMCcode only with 1. Please suggest how can I do it. The code is given below :

ISNULL(CONVERT(VARCHAR(10),PM.PA_AMCCode), '') like          
  (        
   CASE         
    WHEN @AMCCode IS NULL THEN '%'        
    ELSE '%'+@AMCCode+ '%'        
   END        
  )    

This is part of the code where I need to replace the LIKE operator with any other operator which will give the AMCcode with 1 when I want to search AMCcode of 1, not all 10,11,12..... Please help

4
  • 3
    Please, clarify your question. If you need exact match - then why do you use like operator instead of equality? Commented Oct 19, 2015 at 11:50
  • 1
    I'm not positive but you might want to take a look at PATINDEX or CHARINDEX, although I believe they only return an INT, being the location your pattern starts. Commented Oct 19, 2015 at 11:51
  • 1
    yes I need exact match.. . I used equality but it showed no records.. but there are records Commented Oct 19, 2015 at 11:52
  • @gautamshetty Can you post your query you tried using an equality match. Along with samples of what the actual codes look like. If you include sample data and an expected outcome. It's much easier to help with your issue. Commented Oct 19, 2015 at 11:54

2 Answers 2

2

I think you are looking for something like this:

where ',' + cast(PM.PA_AMCCode as varchar(255)) + ',' like '%,' + @AMCCodes + ',%'

This includes the delimiters in the comparison.

Note that a better method is to split the string and use a join, something like this:

select t.*
from t cross apply
     (select cast(code as int) as code
      from dbo.split(@AMCCodes, ',') s(code)
     ) s
where t.AMCCode = s.code;

This is better because under some circumstances, this version can make use of an index on AMCCode.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to exactly match the value, you don't need to use '%' in your query. You can just use like as below

ISNULL(CONVERT(VARCHAR(10),PM.PA_AMCCode), '') like          
  (        
   CASE         
    WHEN @AMCCode IS NULL THEN '%'        
    ELSE @AMCCode        
   END        
  ) 

Possibly you can remove case statement and query like

ISNULL(CONVERT(VARCHAR(10),PM.PA_AMCCode), '') like @AMCCode

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.