日期:2014-05-18  浏览次数:20412 次

求一个sql function
function GetNoRange(@Model),返回一个字符串。
根据@Model查找到表A A.Model列符合条件的 A.No列数据,如:select A.No from A where A.Model=@Model
查找到的结果如 C100,C101,C102,C103...
如果查到的数据是递增的,就把这些数据写成 C100-C103 这样的字符串,
如果不是递增的,就写成C100,C111,C121 这样,用“,”把不是递增的隔开
如果有部分是递增的,写成 C100,C103-C110,C121

注:
A.No 的数据格式是固定的,第一个字符是字母,后面的是整数;




------解决方案--------------------
探讨

汗,需求这样子,你知道的,什么稀奇古怪的需求都有,
我自己写了一个,写了两个小时才写完,晕啊,大家帮我看看有没有问题
SQL code

create function [dbo].fn_GetAmbNoRange(@Model int)
returns varchar
as
begin
declare @ambNoRange varchar(4000)
declare @……

------解决方案--------------------
SQL code
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table # (id int)
insert into #
select 1 union all
select 3 union all
select 4 union all
select 5 union all
select 7

declare @str varchar(100)
;
with gid(gid,id) as
(
    select id - row_number()over(order by id), id from # -- where Model=@Model
), val(val) as
(
    select ltrim(min(id)) + isnull('-'+ltrim(nullif(max(id),min(id))),'') from gid group by gid
)
select @str = isnull(@str+',','')+val from val

select @str --> 1,3-5,7