在SQL CE(精简版)版本3.5中排序字母数字字段

时间:2010-11-26 13:06:16

标签: sorting sql-order-by sql-server-ce alphanumeric

在SQL CE(精简版)版本3.5中对字母数字字段进行排序

TreeNumber是一个nvarchar字段,其值包含数字和字符串。我想对这些记录进行排序,以便包含字母字符的记录位于顶部,其余记录按数字顺序排序。

我想要类似于SQL Server中的以下查询:

SELECT * FROM Tree
ORDER BY 
    (CASE WHEN TreeNumber LIKE '%[a-z]%' THEN 0 ELSE TreeNumber END), TreeNumber

上述查询似乎不起作用,因为CE中不支持[]范围。另一个与SQL Server一起使用但在CE中不起作用的解决方案,因为不支持“IsNumber()”如下:

SELECT * FROM Tree 
ORDER BY 
    (CASE IsNumeric(TreeNumber) WHEN 0 THEN 0 ELSE TreeNumber END), TreeNumber

2 个答案:

答案 0 :(得分:1)

CE中是否支持功能?您可以创建自己的IsNuemric函数(例如,char解析器的简单char),稍后在查询中调用它

答案 1 :(得分:1)

好的,这个解决方案很丑陋,不适合胆小的人。我没有在SQL CE上测试,但它只使用基本的t-sql所以它应该没问题。您将不得不创建一个tally table(只需运行他的第一个代码块,如果您不想阅读它。它使用tempdb以便您想要更改它),以及一个表来保存每个代码。字母表的字母(由于缺乏模式匹配功能)。创建计数表后(您不必像示例所示那样一直到11000),运行这些,您将看到所需的排序行为

创建字母表(temp用于演示目的):

select *
into #alphatable
from
(

select 'A' as alpha union all
select 'B' union all
select 'C' union all
select 'D'
--etc. etc.
) x

创建树表(temp用于演示目的):

select *
into #tree
from
(

select 'aagew' as TreeNumber union all
select '3' union all
select 'bsfreww' union all
select '1' union all
select 'xcaswf' 
) x

解决方案:

select TreeNumber
from
(
select t.*, tr.*, substring(TreeNumber, case when N >  len(TreeNumber) then len(TreeNumber) else N end, 1) as singleChar
from tally t
cross join #tree tr
where t.N < (select max(len(TreeNumber)) from #tree)

) z
left join
#alphatable a
on z.singlechar = a.alpha
group by TreeNumber

order by case when max(alpha) is not null then 0 else TreeNumber end 

这基本上是Moden描述为“单步执行字符”的技术,然后每个字符都连接在alpha表上。 alpha表中没有行的行是数字。