ms sql中的字符串比较

时间:2014-03-21 21:05:52

标签: sql sql-server sql-server-2008

我的桌子上有一些课程标签,如

Subject | Course | 
ACC     | 201
ACC     | 843
ACC     | 843I
ACC     | 850
ACC     | 930

我使用此SQL获取ACC 843,ACC 843I和ACC850:

select Subj_Code, crse_code
        from section_info
        Where (crse_code between '800' and '899') and subj_code = 'ACC'
        order by crse_code

但不知何故,这错过了843I。我怎样才能使这项检查有效?

感谢。

4 个答案:

答案 0 :(得分:2)

select Subj_Code, crse_code
        from section_info
        Where (cast(left(crse_code,3) as int) as num between 800 and 899) and subj_code = 'ACC'
        order by crse_code

希望这有效,试一试让我知道。谢谢!

答案 1 :(得分:2)

假设课程名称的固定格式为3位数后跟可选字母,您只需比较该列的前3个字符即可。此外,由于前3个字符始终为数字,因此您可能希望在比较之前将它们转换为数字。您的查询将变为这样:

select Subj_Code, crse_code
from section_info
Where (cast(left(crse_code,3) as int) between 800 and 899) and subj_code = 'ACC'
order by crse_code

答案 2 :(得分:2)

试试这个:

WHERE crse_code LIKE '8%'

答案 3 :(得分:0)

WITH Orderedcourses AS
(
    SELECT Subj_Code, crse_code,
    ROW_NUMBER() OVER (ORDER BY cast(left(crse_code,3) as int) )AS RowNumber
    FROM Sales.SalesOrderHeader 
) 
SELECT Subj_Code, crse_code, RowNumber  
FROM Orderedcourses
WHERE RowNumber BETWEEN '800' and '899';

这是一个公用表表达式,我创建该表达式来存储用于对课程编号列进行排序的rownumber,然后通过查询调用它来获取列的有序结果。