SQL查询按案例排序

时间:2015-11-30 18:18:08

标签: sql sql-server-2008 sql-order-by

您好,我正在尝试根据案例下订单。这是我的踪迹,我在'END'得到语法错误

有人能告诉我这有什么不对吗?

CREATE TABLE [Emp](
    [Id] [nvarchar](50) NULL,
    [Name] [varchar](50) NULL
) ON [PRIMARY]

GO
insert into emp values ('01','one')
insert into emp values ('02','Two')
insert into emp values ('3','Three')
insert into emp values ('10','Ten')
insert into emp values ('01A','oneA')
insert into emp values ('*','Star')
go
declare @sortby varchar(100)
set @sortby = 'Id'
select * from emp

ORDER BY 
    CASE @sortby
      WHEN 'Id' THEN 
         CASE 
            WHEN ISNUMERIC(Id)=1 
                THEN CAST(Id as int)
            WHEN PATINDEX('%[^0-9]%',Id) > 1 
                THEN CAST(LEFT(Id,PATINDEX('%[^0-9]%',Id) - 1) as int)
            ELSE 2147483648
        END
        CASE 
            WHEN ISNUMERIC(Id)=1 
                THEN NULL
            WHEN PATINDEX('%[^0-9]%',Id) > 1 
                THEN SUBSTRING(Id,PATINDEX('%[^0-9]%',Id) ,50) 
            ELSE Id
        END 
    END,
    Name

0 个答案:

没有答案