0

Im using Microsoft SQL Server which I think is T-SQL or ANSI SQL.

I want to search a database with a string. The matches that fit the begging of the string should come first then sort alphabetically.

I.e. If the table contains FOO, BAR and RAP

a search for the string 'R' should yield:

RAP
BAR

In that order.

Here is my attempt:

SELECT     Name
FROM       MyTable
WHERE      (Name LIKE '%' + @name + '%')
ORDER BY   (IF(Name LIKE @name + '%',1,0)) 

The error message is: "must declare scalar variable @name"

4 Answers 4

3
declare  @name varchar(10)
set @name='R'
SELECT     Name 
FROM       (select 'foo' as name union select 'RAP' union select 'BAR') MyTable 
WHERE      (Name LIKE '%' +  @name  + '%') 
ORDER BY   charindex(@name ,name)
Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution the best, charindex is more compact and gives a better sort ordering.
2

.

DECLARE @name VARCHAR(MAX);
SET @name = 'foo';

SELECT     Name
FROM       MyTable
WHERE      Name LIKE '%' + @name + '%'
ORDER BY   CASE WHEN Name LIKE @name + '%' THEN 1 ELSE 0 END;

1 Comment

This was what I was trying to do with the IF statement.
1

Other solutions seem to miss the "sort alphabetically" part:

DECLARE    @Search VARCHAR(MAX)
SET        @Search = 'R'

SELECT     0, Name 
FROM       MyTable 
WHERE      Name LIKE @Search + '%'
UNION ALL
SELECT     1, Name
FROM       MyTable
WHERE      Name like '%_' + @Search + '%'
ORDER BY   1, 2

1 Comment

This is a clever idea, I tried to do it this way to begin with, but I could not get the union working.
1

Seems that you missed variable declaration:

DECALRE @name varchar(50) -- adjust type and length of variable
SET @name = 'phrase' -- for MSSQL 2008 you can do it in one line

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.