How to query first letter of each character? - c#

I have a table which has three columns: firstname, middlename, lastname. Now, when I type the first letter of each character, the query have to return correctly results.
Example: My database has one record:
When I type the input string as below (just only bold string), the returned results must have the record:
**n** or
**n k** or
**n p** or
**k p** or
**n k p**
I use SQLite, and at the currrent I do not have any idea.
Could you give me a suggestion about this?

You could use wildcard % character to match any string/character and the LIKE statement as well.
For first name that starts with 'N' for example would be:
SELECT * FROM yourTable WHERE FirstName LIKE 'N%'
For first and last name it would be:
SELECT * FROM yourTable WHERE FirstName LIKE 'N%' or LastName LIKE 'P%'
Update:
And if you are not sure if the input is for first name, middle name or last name then you can do it on multiple fields, like:
SELECT * FROM yourTable
WHERE FirstName LIKE 'N%' or MiddleName LIKE 'N%' or LastName LIKE 'N%'
And if there are more than one letter (say two) it would get a little crazier like:
SELECT * FROM yourTable
WHERE FirstName LIKE 'N%' or MiddleName LIKE 'N%' or LastName LIKE 'N%'
or FirstName LIKE 'P%' or MiddleName LIKE 'P%' or LastName LIKE 'P%'
But using the solution above would not be good. So, it would be good that you allow the users to either:
Input letters for each name, that is, a letter for lastname and firstname and middlename if needed
Just input one letter (or of course a String) then search either from firstname, lastname and middlename.
For option number 1 you query would look like this:
SELECT * FROM yourTable
WHERE FirstName LIKE 'N%' or MiddleName LIKE 'K%' or LastName LIKE 'P%'
For option number 2 you query would look like this:
SELECT * FROM yourTable
WHERE FirstName LIKE 'N%' or MiddleName LIKE 'N%' or LastName LIKE 'N%'
or if it a String it would probably look like this:
SELECT * FROM yourTable
WHERE FirstName LIKE 'Ngu%' or MiddleName LIKE 'Ngu%' or LastName LIKE 'Ngu%'
In other words take control of how the users input and give him/her little room for potential error not to mention confusion.

Related

search in sql in multiple column if one is empty then get from another

WITH FilteredClient AS
(
SELECT
Client.ClientId, Client.PersonId, Client.ClientCompanyId,
Client.ClientCategoryId, Client.IsImported, Client.IsModified,
Client.StatusId, Client.ClientTypeId, Client.LeadSourceId,
Person.Company, Person.FirstName, Person.MiddleName,
Person.LastName, Person.AddressLine1, Person.AddressLine2,
Person.AddressLine3, Person.City, Person.State,
Person.Country, Person.Zip,
Person.HomePhone, Person.WorkPhone, Person.CellPhone,
Person.Fax, Person.EmailId, Person.Website,
ClientStatus.ClientStatusName,
ClientCategory.ClientCategoryName,
ClientType.ClientTypeName, LeadSource.LeadSourceName,
[User].Username, Client.AddedBy, [User].UserId
FROM
Client
INNER JOIN
ClientCategory ON Client.ClientCategoryId = ClientCategory.ClientCategoryId
INNER JOIN
Person ON Client.PersonId = Person.PersonId
INNER JOIN
ClientType ON Client.ClientTypeId = ClientType.ClientTypeId
INNER JOIN
ClientStatus on Client.StatusId = ClientStatus.ClientStatusId
INNER JOIN
LeadSource on Client.LeadSourceId = LeadSource.LeadSourceId
INNER JOIN
[User] ON [User].UserId = Client.AddedBy
WHERE
(Client.CompanyId = 1
AND ClientCategory.ClientCategoryName LIKE ('%%')
AND ClientType.ClientTypeName LIKE ('%%')
AND ClientStatus.ClientStatusName LIKE ('%%')
AND LeadSource.LeadSourceName LIKE ('%%')
AND (Person.FirstName + '' + Person.MiddleName + '' + Person.LastName) LIKE ('%Tom%')
AND person.Company LIKE ('%Tom%'))
)
SELECT
ClientId, PersonId, ClientCompanyId, ClientCategoryId,
IsImported, IsModified, StatusId, ClientTypeId, LeadSourceId,
Company, FirstName, MiddleName, LastName,
AddressLine1, AddressLine2, AddressLine3,
City, [State], Country, Zip,
HomePhone, WorkPhone, CellPhone, Fax, EmailId, Website,
ClientStatusName, ClientCategoryName, ClientTypeName,
LeadSourceId, LeadSourceName, Username, AddedBy, UserId
FROM
FilteredClient
Now I searched according to ClientName (client name includes CompanyName and person's first name). Both have seperate column in Person table.
I put text in textbox then click on search then the value of textbox goes to both company.person and person.firstname .
Now I want the search result to come from both column but if there is some match found in companyname then it pick companyname and related person name but if i put person name in textbox then in if company column has 0 result then it is not searched in person firstname
Please tell me if any mistake in my condition
Please help me
You are using AND clause in where condition its a mistake as per your requirement.You should use OR clause instead of AND so replace your query with following
AND ((Person.FirstName +''+Person.MiddleName +''+Person.LastName) like ('%Tom%')
OR person.Company like('%Tom%'))
take a look at this answer. this may help you tune your algorithm and adapt your requirement on it:
This Link

How to return a column when checking for duplicates?

I need to find all records that the FIRSTNAME is a Duplicate and the LASTNAME is a duplicate
So my data kinda looks like this:
FirstName LastName CustomerFileLocation
Joe Smith c:\file1
Joe Jones c:\File2
Joe Smith c:\File3
Harry Smith c:\File4
I want the query to return
Joe Smith c:\file1
Joe Smith c:\File3
I wrote this to select them, but it if I add the CustomerFileLocation to the GROUP BY expression it returns nothing.
SELECT FirstName, LastName, COUNT(1) AS CNT, CustomerFileLocation
FROM tblCustomerList
WHERE (Skip = 0)
GROUP BY FirstName, LastName
HAVING (COUNT(1) > 1)
You can try using a subquery to return the table containing any records that have a count greater than 1 then inner join your table back on that subquery.
Haven't tried it but it would look something like this.
SELECT tblCustomerList.FirstName, tblCustomerList.LastName, tblCustomerList.CustomerFileLocation From (SELECT FirstName, LastName, COUNT(1) AS CNT, CustomerFileLocation
FROM tblCustomerList
WHERE
GROUP BY FirstName, LastName
HAVING (COUNT(1) > 1))) as countTable inner join tblCustomerList
on countTable.lastname = tblCustomerList.lastname and countTable.firstname = tblCustomerList.firstname and tblCustomerList.Skip = 0
SELECT (FirstName + ' ' + LastName) as fullname,
cast(CustomerFileLocation as nvarchar) as location
FROM tblCustomerList WHERE (Skip = 0) GROUP BY (FirstName + ' ' + LastName),
cast(customerFileLication as nvarchar) having count(1)>1
I haven't tested or tuned it for performance but something along this line must work.

Using String.Contains() across multiple columns in EF6 model

I feel like this is something simple and I'm just missing it...
Need to do a quick and dirty text search on FirstName and LastName columns together from a model like this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Sample data:
FirstName LastName
-------------------------------
John Appleseed
John Anderson
Chris Cringle
George Washington
Backend is SQL Server, using LINQ to Entities and Entity Framework 6, I need to do a lookup on the full name, but something like this won't work:
var results = from p in db.Persons
where (p.FirstName + ' ' + p.LastName).Contains(keyword)
select p;
LINQ doesn't like that. This is for an autocomplete method; I want it to be able to find the results for "john a" if somebody types that -- it would be the first two rows from the sample data.
How can I do it?
EF can only concat strings; it cannot concat characters. Were it LINQ to Objects the char would be converted to a string without any problems, but EF just isn't robust enough to do that. The fix is trivial enough though; use a literal string, not a literal character, for the space:
var results = from p in db.Persons
where (p.FirstName + " " + p.LastName).Contains(keyword)
select p;

How to manipulate values to use as parameters

Hi I have a select and a text type input. These controls are used to filter list in a datagrid. The select control has the following options: LastName, MiddleName, FirstName, Gender, City and StudentID. Then I was given this query:
SELECT * FROM Student
WHERE ( LastName LIKE '%' + #LastName + '%' OR #LastName = '' )
AND ( MiddleName LIKE '%' + #MiddleName + '%' OR #MiddleName = '' )
AND ( FirstName LIKE '%' + #FirstName + '%' OR #FirstName = '' )
AND ( Gender LIKE '%' + #Gender + '%' OR #Gender = '' )
AND ( City LIKE '%' + #City + '%' OR #City = '' )
AND ( StudentID LIKE '%' + #StudentID + '%' OR #StudentID = '' )
So for example, the user selects First Name then typed in "James". That could be read as "Give me the list of students whose First Name is 'James'." In my controller, the only way I thought is using If..Else If or Switch condition. It was like this:
string lastName = String.Empty;
string middleName = String.Empty;
and so on..
if(dropdown == "Lastname")
{
lastName = textbox_value;
}
else if(dropdown == "Middlename")
{
middleName = textbox_value;
}
and so on..
Then I have method which will pass the values as parameters to my sql query.
resultList = GetRecord(lastName, middleName, firstName, gender, city, studentID);
My question now is, what is the better way, the cleanest and simplest, than using If..Else and Switch?
You need to decide it somewhere , either in your controller or you can delegate this to another class but delegating it to another helper class will takeout the responsibility. so i would say , you may think of below design
public class ParameterSelector
{
private Dictionary<string,Action> _dictActionMap = new Dictionary<string, Action>();
public ParameterSelector()
{
PopulateDictionaryWithActions();
}
private void PopulateDictionaryWithActions()
{
_dictActionMap.Add("LastName", () => lastName = txtBox_Value);
_dictActionMap.Add("MiddleName", () => middleName = txtBox_Value);
}
}
and usage
main()
{
if(_dictActionMap.ContainsKey(dropdown))
_dictActionMap[_dictActionMap]();
}
see to avoid ifs and switches , i used dictionary with relevant actions, this approach has its own drawback for example , we have unnessary actions defined to handle the part of switch / ifs , its give a feeling that we have get rid of ifs/switch but have tradeoffs with memory requirement so never complicate things which can be handle with simplicity.
so i would say using of Ifs/ Switch has nothing wrong in your case.
You can look at using a switch (C# Reference) statement.
The switch statement is a control statement that selects a switch
section to execute from a list of candidates.

How do I execute a MySQL parameterized query in C#?

When I run this command in MySQL:
SELECT * FROM v
WHERE v.firstname LIKE '%a%' OR middlename LIKE '%a%' OR lastname LIKE '%a%'
It returns 4 rows in the result set.
But when I run the same query using parameters in C# it returns only one.
SELECT * FROM v
WHERE v.firstname LIKE ?word OR middlename LIKE ?word OR lastname
cmd.Parameters.AddWithValue("word", '%'+key+'%');
I also tried '%' ?word '%' and adding the parameter (key) only, but this didn't work either.
How do I make this work?
Are you using something like:
cmd.ExecuteScalar()
in your code? It will return only 1 record. Try
cmd.ExecuteReader()
instead.
It looks like you're missing "LIKE ?word" at then end of your second SQL statement.
WHERE v.firstname LIKE ?word OR middlename LIKE ?word OR lastname
are you missing lastname LIKE ?word ?

Categories