views:

52

answers:

4

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"

+2  A: 

.

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;
Dave Markle
This was what I was trying to do with the IF statement.
Robert
+3  A: 
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)
Madhivanan
I like this solution the best, charindex is more compact and gives a better sort ordering.
Robert
+1  A: 

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
Grzegorz Gierlik
+1  A: 

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
devio
This is a clever idea, I tried to do it this way to begin with, but I could not get the union working.
Robert