Basically I have a table like this:
CREATE TABLE Person(
PersonID int IDENTITY(1,1) NOT NULL,
FirstName nvarchar(512) NOT NULL,
LastName nvarchar(512) NULL
)
And I need to find the top n results based on a user-query like this:
"Joh Smi"
The following query returns the results I need (I think). Just not in the relevant order.
SELECT
PersonID, FirstName, LastName
FROM
Person
WHERE
FirstName LIKE 'Joh%' OR
LastName LIKE 'Joh%' OR
FirstName LIKE 'Smi%' OR
LastName LIKE 'Smi%'
If the following names were in the database and our user-query was "Joh Smi" the names should appear in the following order (or similar)
I'm hoping to get it to work similar to facebook's autocomplete friend-search.
So, how do I return the top n most relevant rows in SQL Server 2008?
Code: SELECT. left(NAME, charindex(' ', NAME) - 1) AS 'FirstName', REVERSE(SUBSTRING(REVERSE(NAME), 1, CHARINDEX(' ', REVERSE(NAME)) - 1)) AS 'LastName'
If you'd like to see the latest date first and the earliest date last, you need to sort in descending order. Use the DESC keyword in this case. ORDER BY ExamDate DESC ; Note that in T-SQL, NULL s are displayed first when sorting in ascending order and last when sorting in descending order.
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
To get the first and last record, use UNION. LIMIT is also used to get the number of records you want.
I recommend implementing Full Text Search (FTS) for two reasons:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With