Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# SQL
String sql = "select PatientId, FirstName, LastName, Sex, Age, CNIC, Phone, GaurdianName from Patients WHERE 1=1";
            if (PatientId.Text != "")
            {
                
               sql += " AND PatientId LIKE '%" + PatientId.Text + "%'";
            }
            
i couldn't uderstand where is wrong!! i want to retrieve exact patient id but not getting like if i query for 1 it is showing 1,10,11 records!! i couldn't fighure out where is the problem.
Posted 1-Jun-13 16:50pm
Edited 1-Jun-13 18:05pm
v2
Comments
ThePhantomUpvoter at 1-Jun-13 23:53pm
   
"1 it is showing 1,10,11 records" and so it should. Do you have any idea what LIKE does? That is the output that I would expect. If you want the exact PatientId then you just need to use =
David_Wimbley at 2-Jun-13 0:05am
   
Should make that the answer, would have my 5
Faraz the fighter at 2-Jun-13 0:52am
   
sql += " AND PatientId == + PatientId.Text + ";
 
not giving the required result
aspnet_regiis -I at 2-Jun-13 2:00am
   
== should be = since it is sql syntax
debkumar@codeproject at 2-Jun-13 0:07am
   
What is the use of 1=1? Unnecessarily adding clause. I believe query optimizer removes this from the query.
 
'LIKE' and '%' are used for finding elements based on substrig (ignoring case sensitivity). '=' is used for finding exact (ignoring case sensitivity).
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

To add to what the others have said, don't do it like that anyway.
Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

To get exact match, your query should looks like:
SELECT PatientId, FirstName, LastName, Sex, Age, CNIC, Phone, GaurdianName
FROM Patients
WHERE PatientId LIKE =@PatientId
 
I would suggest you to create stored procedure and call it from code behind.
Using a Stored Procedure with Output Parameters[^]
How to create a SQL Server stored procedure with parameters [^]
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 2 Jun 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100