SQL语法错误

时间:2010-06-08 10:17:34

标签: sql sql-server tsql

我正在使用Microsoft SQL Server,我认为它是T-SQL或ANSI SQL。

我想用字符串搜索数据库。应首先匹配字符串的匹配,然后按字母顺序排序。

即。如果表格包含FOOBARRAP

搜索字符串'R'应该产生:

RAP
BAR

按顺序。

这是我的尝试:

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

错误消息是:“必须声明标量变量@name”

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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;

答案 2 :(得分:1)

似乎您错过了变量声明

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

答案 3 :(得分:1)

其他解决方案似乎错过了“按字母顺序排序”部分:

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