求一个sql function

hjsmliang2008 2012-03-15 09:46:16
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 的数据格式是固定的,第一个字符是字母,后面的是整数;


...全文
75 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hjsmliang2008 2012-03-16
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 vidor 的回复:]

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

……
[/Quote]

感谢 Vidor(莫逆),你的语句确实可行,而且效率更好
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 hjsmliang2008 的回复:]

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

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

自己解决了就好,恭喜啊,顺带学习了
hjsmliang2008 2012-03-15
  • 打赏
  • 举报
回复
汗,需求这样子,你知道的,什么稀奇古怪的需求都有,
我自己写了一个,写了两个小时才写完,晕啊,大家帮我看看有没有问题

create function [dbo].fn_GetAmbNoRange(@Model int)
returns varchar
as
begin
declare @ambNoRange varchar(4000)
declare @amb_no_next varchar(5)
declare @amb_no_restone varchar(5)
declare @No int
declare @Num int

set @ambNoRange=''
set @amb_no_next=''
set @amb_no_restone=''
set @No=0
set @Num=0

declare curNo cursor local for
select substring(A.No,2,len(amb_no))as Num,A.No
from A
where A.Model = @Model
order by cast(substring(A.No,2,len(A.No)) as int)

open curNo

fetch next from curNo into @No,@amb_no_next
while(@@FETCH_STATUS = 0)
begin
if(@Num = @No)
begin
set @ambNoRange=replace(@ambNoRange,'-'+@amb_no_restone,'')
set @ambNoRange=@ambNoRange+'-'+@amb_no_next
end
else
begin
if @ambNoRange=''
set @ambNoRange=@amb_no_next
else
set @ambNoRange=@ambNoRange+','+@amb_no_next
end
set @Num = @No+1
set @amb_no_restone=@amb_no_next
fetch next from curNo into @No,@amb_no_next
end

return @ambNoRange
end

  • 打赏
  • 举报
回复


要求真多啊,都写成逗号隔开不行吗?
Vidor 2012-03-15
  • 打赏
  • 举报
回复
--> 测试数据:#
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

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧