高难度的Sql问题!!
我想实现类似下面语句的效果:
select * form table where key in (a,b,g,c,a,...);
详细要求:
1、in 中的列表内容有可能是重复的,也允许重复
2、要求返回结果严格按照IN 列表的顺序返回,对于重复的key内容也要返回重复的结果纪录
3、需要在一个sql语句中实现上面要求,尽量不使用临时表
一句没法!
declare @sql nvarchar(4000)
declare @str varchar(100)
set @str='a,b,c,d,a,b,c'
set @sql='select top 1 * from table where key='''+replace(@str,',',''' union all select top 1 * from table where key=''')+''''
exec(@sql)
我想也只有使用union,但语句会很长。
select * form table where key =a
union all
select * form table where key =b
union all
select * form table where key =g
union all
select * form table where key =c
union all
select * form table where key =a
...
以下存储过成测试通过:
create proc proc_orderbykey
@p varchar(1000)
as
declare @sql varchar(8000)
set @sql='insert @temp(value) values('
select @sql=@sql+replace(@p,',',') insert @temp(value) values(')+')'
set @sql='declare @temp table (id int IDENTITY(1,1),value int)
'+@sql+'
select b.* from tablename b,@temp t
where b.key=t.value
order by t.id
'
exec (@sql)
go
调用:
exec proc_orderbykey '1,4,6,8,2,3,4,1,8,7'
这个是假设key的类型是整数的,如果是字符型,也能写,但是会多很多引号,容易出错。
declare @str varchar(8000)
set @str='a,b,c,d'
set @str ='create table #aa (aa char(1) null) insert into #aa (aa) values(''' + REPLACE(@str,
',',''') insert into #aa (aa) values(''' ) + ''')'
exec(@str)
select * from #aa