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 Server 2008 定时作业的制定
--1.打开【SQL Server Management Studio】,在【对象资源管理器】列表中选择【SQL Server 代理】;
--2.鼠标右击【SQL Server 代理】,选择【启动(S)】,如已启动,可以省略此步骤;
--3.展开【SQL Server 代理】列表,右击【作业】-->【新建作业】;
--3.1 在【常规】选项卡中:
......
--SQL解密ctext字段内容函数
--exec sp_decrypt '约束名称'
--exec sp_decrypt 'DF_InsuranceRecord_PeriodUnit'
--exec sp_decrypt '存储过程名称'
--exec sp_decrypt 'sp_SearchPrinting_InsuranceRecord'
--主要用途:读取systemcomments中的字段内容。包括约束,存储过程等等。
--原文应该来自http://blog.csdn.net ......
上次做了个项目,涉及到数据库的还原和恢复,到网上找了一下,是利用SQLDMO实现的,只要添加SQLDMO引用就好了,然后利用下边的类的方法就可以实现了。
我把原作者的类扩充了一下,可以自动识别web.config里 的数据库连接字符串,可以通过变量设置还原恢复的信息。
需要注意的时还原,还原的时候问题最大了,有别 ......
具体要注意的:
1.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:
select id from t where num is null
可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:
select id from t where num=0 &n ......
SQL like子句的另一种实现方法,速度比like快(转)
一般来说使用模糊查询,大家都会想到LIKE
select * from table where a like '%字符%'
如果一个SQL语句中用多个 like模糊查询,并且记录条数很大,那速度一定会很慢。
下面两种方法也可实现模糊查询:
select * from table where patindex('%字符%',a)>0 ......