重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
都是基于resultSet的遍历,定义一个集合,先查出A表的所有数据,然后循环取出字段B的值,然后再定义一个集合,取出C表的数据,再取出B字段的值,然后二者相等的数据,放入第三个集合中,这样就可以了。
创新新互联,凭借10年的网站设计制作、网站设计经验,本着真心·诚心服务的企业理念服务于成都中小企业设计网站有1000多家案例。做网站建设,选创新互联公司。
Create Table Tb
(
Pid Varchar(50),
CEID Varchar(50),
Level int,
Ccode Varchar(50),
pCode Varchar(50)
)
Insert Into TB Values('','1',0,'产品1','')
Insert Into TB Values('1','2',1,'Test1','产品1')
Insert Into TB Values('1','3',1,'Test2','产品1')
Insert Into TB Values('2','4',2,'Test11','Test1')
Insert Into TB Values('2','5',2,'Test12','Test1')
Insert Into TB Values('3','6',2,'Test21','Test2')
Insert Into TB Values('3','7',2,'Test22','Test2')
Insert Into TB Values('6','8',3,'Test211','Test21')
Insert Into TB Values('6','9',3,'Test212','Test21')
Insert Into TB Values('6','10',3,'Test213','Test21')
With T
As
(
Select Pid,CEID,Ccode,Level,Convert(Varchar(4000),CEID) As Path From TB Where Pid=''
Union All
Select TB.Pid,TB.CEID,TB.Ccode,TB.Level,Convert(Varchar(4000),T.Path+'-'+TB.CEID) From TB inner join T On TB.Pid=T.CEID
)
Select replicate(' ',level)+Ccode As Ccode From T
Order By Path
使用sqlserver递推查询,可以直接查询出来。
参考资料:
WITH lmenu(nav_id,nav_name,nav_parentid,level) as
(
SELECT nav_id,nav_name,nav_parentid,0 level FROM nav nav_parentid=0
UNION ALL
SELECT A.nav_id, A.nav_name,a.nav_parentid, b.level+1 FROM gs_nav A,lmenu b where a.nav_parentid= b.nav_id and nav_id = 10
)
SELECT * from lmenu
具体SQL语句还需要自己验证一下,上面的自己看着乱写的。
sql1=select * from (select *, row_number() over(order by username ) as rowNumber from users where regfrom='admin') as t where t.rowNumber 0 and t.rowNumber = 0 + 30 order by username
怎么会有27 条记录呢,除非你的表 一共就27条记录吧。
用游标或临时表
--游标
declare youbiao1 for 查询1
open youbiao1
fetch next from youbiao1 into 变量
while @@FETCH_STATUS = 0
begin
里面一次套用
end
--临时表
declare @ID int
set @ID = 1
while Exists(select * from 表)
begin
--处理
--
set @ID = @ID + 1
end
有游标循环即可。
decalre @fieldName varchar(128)
declare @sql varchar(max)
set @sql='select row_number() '
declare MyCur cursor for select ID form table1
open
fetch next from MyCur into @FieldName
while @@fetch_status = 0
begin
@sql=@sql +','+@FieldName
fetch next from MyCur into @FieldName
end
set @sql =@sql +' from tablename'
exec(@sql)
--关闭释放游标
--T_Sql查询
select a.Name as tableName from sysobjects a inner join syscolumns b on a.ID=b.ID
where b.Name='字段名'
给分!