sql递归查询
在工作中遇到一个问题,是需要sql递归查询的.不懂,于是到csdn上去问,那里的效率真是非常高,我以前也没在上面问过问题.
问题描述:
我有一个表结构如下:
id upperid
1 2
3 2
4 1
5 3
具体层次不知道,我想用递归sql语句把所有属于某个upperid的数据,包括它的子树,都读出去,请问应该子怎么写?
比如说 upperid =2
那么先找到1,3,然后再由1,3找到4,5
使用sql语句实现
有两位朋友都给了回复:
fa_ge(鶴嘯九天)
Create table t(id int,upperid int)
insert into t
select 1, 2
union all select 3, 2
union all select 4, 1
union all select 5, 3
select * from t
create function aa(@upperid int)
returns @t table (id int,upperid int,level int)
as
begin
declare @i int
set @i=1
insert into @t
select *,@i from t where upperid=@upperid
while @@rowcount>0
begin
set @i=@i+1
insert into @t
select a.*,@i from t a left join @t b on a.upperid=b.id
where b.level=@i-1
end
return
end
select * from dbo.aa(1)
id upperid level
----------- ----------- -----------
4 1 1
(所影响的行数为 1 行)
select * from dbo.aa(2)
id upperid level
----------- ----------- -----------
1 2 1
3 2 1
4 1 &nbs
相关文档:
嵌入SQL语言:
我将一个sql链接到数据库,该数据库名为master(系统数据库)
then 给数据库添加新表,建立三个key:userid(int),name(char(10)),password(char(10))
在窗体中弄三个textbox控件,分别定义Name属性为userid,name,password;
再来一个button
以下是Form1.cs中的代码
using System;
using System.Coll ......
转载自:http://www.neatstudio.com/index-4.shtml
文章来自寂寞hacker,http://hi.baidu.com/isbx/blog/item
/08ef48547ef1ad58574e00bf.html:
当前的Web开发者中肯定有不少人没有注意到作者所提到的这两个问题的。
第一个问题是这样的,MySQL默认有一个配置参数
max_packet_size,这个参数是用于限制MySQL客户端和My ......
在SQL server中经常会转换string到datetime类型,最常用的函数就是Convert。那么对Convert这个函数,不得不详细的研究一下。Convert这个函数的功能很强大,格式又很简单CONVERT ( data_type [ ( length ) ] , expression [ , style ] )。单就将string到datetime类型的转换就有很多样式。如: Convert(datetime, expression), ......
SQL like子句的另一种实现方法,速度比like快(转)
一般来说使用模糊查询,大家都会想到LIKE
select * from table where a like '%字符%'
如果一个SQL语句中用多个 like模糊查询,并且记录条数很大,那速度一定会很慢。
下面两种方法也可实现模糊查询:
select * from table where patindex('%字符%',a)>0 ......