首页 - 数据库 - SQL Server

根据排序定义表排序数据

发布时间: 2007-04-19 05:04    作者: 未知    来源: 未知    浏览:    评论


/*--原帖地址:http://community.csdn.net/Expert/topic/3866/3866872.xml?temp=.2154199--*/

--测试数据create table tb1(id int,col1 varchar(10),col2 int)insert tb1 select 1,'aa',111union  all select 2,'aa',111union  all select 3,'aa',111union  all select 4,'bb',222union  all select 5,'bb',222  union  all select 6,'cc',333  union  all select 7,'cc',333  union  all select 8,'cc',333union  all select 9,'cc',333 

create table tb2(col1 varchar(10),size int)insert tb2 select 'aa',2union  all select 'cc',2  --改改顺序union  all select 'bb',0go

/*--处理要求:

tb1 与 tb2 通过 col2 关联,tb2的col1包含所有tb1.col1

要求写函数实现如下排序:tb1中的col1按照tb2中的col1定义的记录数,进行排列。如:在tb2中:aa 的size=2,就先排2条aa记录cc 的size=2, 并且在aa后面,所以接着排2条cc的记录而bb 在tb2中定义是0条,则不参与排序,始终显示在最后重复循环,不够的由后面的记录补上

最终实现如下排序结果:

id          col1       col2        ----------- ---------- ----------- 1           aa         1112           aa         1116           cc         3337           cc         3333           aa         1118           cc         3339           cc         3334           bb         2225           bb         222--*/

--排序函数create function f_sort(@id int,@col1 varchar(10))returns varchar(20)asbegin declare @i int,@size int,@j int set @i=0 select @i=case when @size is null then @i+1 else @i end  ,@size=case when @col1=col1 then size else @size end from tb2 if @size=0 return(replicate(20,'9')) select @j=count(*) from tb1 where id<@id and col1=@col1 return(right(10000000000+isnull(@j,0)/@size,10)+right(10000000000+@i,10))endgo

--调用实现查询select * from tb1 aorder by dbo.f_sort(id,col1)go

--删除测试drop table tb1,tb2drop function f_sort

TAG

Smile Big Smile Surprise Stick out tongue Wink Sad Tongue Tied Indifferent Crying Embarrassed Cool Angry Angel Devil [8-|] [:#] [:-*] [:^)] [<:o)] [|-)] Yes Beer Left Hug Music Star Time Snail Pizza Automobile Umbrella Computer Storm [mo] [8o|] [^o)] [+o(] [*-)] [8-)] Coffee No Drinks [Z] Right Hug Cake Broken Heart Gift Wilted Flower Movie Dog Idea Sleep Email Travel Paradise
呢称:

加粗 斜体 下划线 链接 图片 代码 邮件地址 引用 列表

最多只能输入100个字符

Tags

SQL 数据库 asp.net C# XML 控件 .NET教程 程序 事件 数据 安全 代码 Server 客户端 验证 数据库专栏 接口 文件 Oracle DataSet 函数 DataGrid 问题 .net return C#语言 JavaScript 服务 IIS 对象 语句 windows 继承 时间 web.config 设计 开发 参数 变量 解决 字符 ADO.net 环境 VB.Net语言 web 异常 工具 服务器 计算 实例 OLEDB Application VB Word WebService insert asp net 安装 记录

精华推荐

更多

精品下载

更多