如何在sql server中使用“like”搜索数据

时间:2013-05-15 14:24:48

标签: sql-server sql-server-2008

我输入了一个单词“boat”,所以我需要以船开头的记录,还包含“船”。但以“船”开头必须首先出现

我试过了

Select   AsiccCodeId,AsiccDescription             
FROM     AsiccCodeMaster  c             
WHERE    c.AsiccDescription like 'boat%' or c.AsiccDescription like '%boat%'

select a.* from
(

 Select   AsiccCodeId,AsiccDescription             
 FROM     AsiccCodeMaster  c             
 WHERE c.IsActive = 1  and (GoodFor = 'M' or GoodFor = 'B')
 and c.AsiccDescription like 'Unmilled%'



 UNION

 Select   AsiccCodeId,AsiccDescription             
 FROM     AsiccCodeMaster  c             
 WHERE c.IsActive = 1  and (GoodFor = 'M' or GoodFor = 'B')
 and c.AsiccDescription like '%Unmilled%'



 )a

但它给了我

4137    Combustion Boats 
6360    Boat, Fibre
6361    Boat, Rubber - Motorized
6362    Boat, Wooden Canal Boats
6363    Boat, Wooden With Engine
6370    Wooden Boats Body Building
6374    Boat, Rowing / Sports
6375    Boat, Rubber - Nonmotorized
6376    Boat, Wooden Without Engine-Others
6379    Parts Of Ships, Boats Etc., N.E.C
6391    Ships, Boats & Other Vessels, N.E.C
6394    Ships, Boats & Other Vessels, N.E.C

我需要先以“boat”开头的记录,然后再记录包含“boat”的记录

2 个答案:

答案 0 :(得分:10)

在Order By子句中使用CASE语句

SELECT   AsiccCodeId,AsiccDescription             
FROM     AsiccCodeMaster  c             
WHERE    c.AsiccDescription like '%boat%'
ORDER BY CASE WHEN c.AsiccDescription like 'boat%' THEN 0 ELSE 1 END, c.AsiccDescription

由于您希望以“船”开头的标题首先出现,因此CASE语句将优先考虑这些标题。它查看每条记录,如果描述以'boat'开头,则为其分配一个排序值0,否则它会为其分配一个排序值1. ORDER BY默认按升序排序,因此它将全部放入0(在所有1(剩余记录)之前以“船”开头的那些

答案 1 :(得分:3)

您需要对结果进行一些订购!

SELECT a.* 
FROM
(
    SELECT 
       AsiccCodeId, AsiccDescription, Sequence = 1
    FROM AsiccCodeMaster  c             
    WHERE c.IsActive = 1 AND (GoodFor = 'M' or GoodFor = 'B')
      AND c.AsiccDescription LIKE 'Boat%'    

    UNION

    SELECT 
       AsiccCodeId, AsiccDescription, Sequence = 2
    FROM AsiccCodeMaster  c             
    WHERE c.IsActive = 1 AND (GoodFor = 'M' or GoodFor = 'B')
      AND c.AsiccDescription LIKE '%Boat%'    
) a
ORDER BY a.Sequence