首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql记录查询,高手帮解决一下!解决办法

2012-02-12 
sql记录查询,高手帮解决一下!!!表A中有dabh字段,为varchar类型,,如果我想selectdabhfromAorderbydabh则显

sql记录查询,高手帮解决一下!!!
表   A   中有dabh字段,为varchar类型,
,如果我想   select   dabh   from   A   order   by   dabh   则显示
      dabh                                     而我最终想查询为:
---------               ---------
1           null                               1           null    
2           0                                     2           0    
3           1                                     3           1
4           10                                   4           10  
5           101                                 5           12
6           12                                   6           20
7           20                                   7           101  
8           ...                                 8           ...
100       a1                                   100       a1    
101       b1                                   101       b1    
xxx       ...                                 xxx       ...          

注:把null排到最前,然后把数字排到后面,最后把字母开头的放到最后,
        最后用一条SQL语句查询出来

        自己也做了一点用union连接:
    select   dabh   from   A   where   dabh   is   null   order   by   dabh  
union  
    select   dabh   from   A     where   not   dabh   is     null   and   dabh   not   like   '[a-z]% '   order   by   cast(dabh   as   int)  
union
    select   dabh   from   A     where   not   dabh   is     null   and   dabh   like   '[a-z]% '   order   by   dabh

    单用一句行,连接到一起就错。

    请高手指点一下。

[解决办法]
try

Select * From A
Order By (Case When dabh Is Null Then 0 Else


(Case When IsNumeric(dabh) = 1 Then Cast(dabh As Int) Else 99999 End) End)
[解决办法]
--創建測試環境
Create Table A
(dabh varchar(50))
Insert A Select null
Union All Select '0 '
Union All Select '1 '
Union All Select '10 '
Union All Select '101 '
Union All Select '12 '
Union All Select '20 '
Union All Select 'a1 '
Union All Select 'b1 '
GO
--測試
Select * From A
Order By (Case When dabh Is Null Then 0 Else
(Case When IsNumeric(dabh) = 1 Then Cast(dabh As Int) Else 99999 End) End)
GO
--刪除測試環境
Drop Table A
--結果
/*
dabh
NULL
0
1
10
12
20
101
a1
b1
*/

热点排行