首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么按照给出的数字大小讲多列按照此优先级排序

2012-04-03 
如何按照给出的数字大小讲多列按照此优先级排序?是这样的,有一个学生表,里面存入学生的基本信息专业,年级,

如何按照给出的数字大小讲多列按照此优先级排序?
是这样的,有一个学生表,里面存入学生的基本信息

专业,年级,班级,寝室号

我想现在写一个存储过程,分别传入排序时这些列的优先级数字

比如 专业 = 1,寝室号 =2,班级=3,年级=4

那么按照从大到小的优先级排序,先查找相同年级的同学,排在最前面,然后在剩下来的同学中一次按照 班级,寝室号,专业排序

最后给出整个排序完的学生列表..

小弟为了这个东西想了两天了,能力有限,临时表什么的都用上了还是无解,请各位大大指点一二.

[解决办法]
存储过程用动态SQL去实现!

SQL code
create proc get_All(@order varchar(1000))asbegindeclare @sql varchar(8000)set @sql = 'select * from tb 'if @order is not nullset @order = replace(replace(@order,' 1,',' asc,'),' 0,',' desc,')else set @order = ''set @sql = @sql + ' ' + left(@order,len(@order)-1)exec(@sql)endgo--> testexec get_All 'id 1,name 0,'  --注意后边有 , 号!
[解决办法]
SQL code
create table tb(id int,name varchar(10))insert into tbselect 1,'a' union allselect 1,'b' union allselect 2,'c' union allselect 2,'a' union allselect 11,'c'gocreate proc get_All(@order varchar(1000))asbegindeclare @sql varchar(8000)set @sql = 'select * from tb 'if @order is not nullset @order = ' order by ' + replace(replace(@order,' 1,',' asc,'),' 0,',' desc,')else set @order = ''set @sql = @sql + ' ' + left(@order,len(@order)-1)exec(@sql)endgo--> testexec get_All 'id 1,name 0,'  --注意后边有 , 号!drop proc get_Alldrop table tb/*******************id          name----------- ----------1           b1           a2           c2           a11          c(5 行受影响)
[解决办法]
SQL code
create table test1015(专业 int,寝室号 int,班级 int,年级 int)insert into test1015select 1,11,1,1 union allselect 1,11,2,1 union allselect 1,12,3,1 union allselect 2,9,1,2 union allselect 2,9,2,2 union allselect 2,8,3,1declare @param varchar(30)set @param='年级,班级,寝室号,专业' --不需要1,2,3,4你直接控制它们的位置就可以了。declare @sql varchar(8000)set @sql='select * from test1015 order by '+@paramexec(@sql)drop table test1015/*专业          寝室号         班级          年级----------- ----------- ----------- -----------1           11          1           11           11          2           12           8           3           11           12          3           12           9           1           22           9           2           2*/ 

热点排行
Bad Request.