
在 SQL 中,你可以使用递归查询来实现递归函数。递归查询是一种查询,其中结果集由一条或多条 SELECT 语句和一条用于查找下一级行的 UNION ALL 语句组成。
例如,假设你有一张表,其中包含父子关系的信息(即,每个记录都有一个父级 ID,表示它的父级),你可以使用以下递归查询来查询每个记录的所有祖先:
WITH RECURSIVE ancestors AS (
-- 初始查询
SELECT id, parent_id
FROM your_table
WHERE id = :your_id
UNION ALL
-- 递归查询
SELECT tid, tparent_id
FROM your_table t
INNER JOIN ancestors a ON tid = aparent_id
)
SELECT id FROM ancestors;
在这个查询中,我们使用了一个递归关系,其中第一个 SELECT 语句是初始查询,用于查询给定 ID 的记录。第二个 SELECT 语句是递归查询,用于查询与当前记录的父级相关的记录。通过将这两个 SELECT 语句用 UNION ALL 连接起来,我们就可以获得所有祖先的列表了。
用递归做:
添加一个页面的全局变量 string tempStr = "";
方法:
//ide是指要查询的id 比如要查询5的路径 就dg(5);
void dg(int ide)
{
tempStr = tempStr + idetoString() + " ";
//不知道你是怎么写的数据库连接类 所以只写了语句昂 dbHelper是指数
//据库 *** 作类库 getparntId应该是通过id得父id的方法 语句如下:
//在这里需要一个特殊处理 就是如果没有父id 则返回0
int i = dbHelpergetparentId("select parentId from tb_knowledge where id = "+ide);
//如果还有父节点的话 再次调用自己
if(i != 0)
dg(i);
}
void main()
{
//在这里打比方说要查询5的路径
dg(5);
//打印结果 调用dg(ide)方法后 tempStr里就是正确路径了
print(tempStr);
}
这样就能实现了 用递归做不很难 而且效率不高
//--------以下是用控制台写的一个多路径测试----
class Program
{
static void Main(string[] args)
{
Class1 tempcls = new Class1();
//在这里打比方说要查询5的所有路径
pathPoint p = new pathPoint();
//就设置p的ID为5
ppointId = 5;
//调用递归方法 以p(id为5的节点)为参数
tempclsdg(p);
//调用打印结果的方法
tempclsprintPath(p);
ConsoleReadLine();
}
}
public class Class1
{
//打印结果的方法 随便写的 没考虑多层的问题 不过大概就是这么个意思了
public void printPath(pathPoint p)
{
foreach (pathPoint temp in pppList)
{
ConsoleWrite(ppointId);
if (temppointId != 0)
{
ConsoleWrite(" > ");
printPath(temp);
ConsoleWriteLine();
}
}
}
//递归方法
public void dg(pathPoint pp)
{
//查出pp的所有子节点
DataTable dt = DBHelperQueryDataTable("select parentId from tb_knowledge where id = " + pppointId);
//循环dt
for (int j = 0; j < dtRowsCount; j++)
{
//声明一个新的节点
pathPoint ptemp = new pathPoint();
//将第j个子节点的id赋值给这个新的节点
ptemppointId = ConvertToInt32(dtRows[j][0]);
//把这个新节点添加到pp的子节点列表中 就是把子节点添加到父节点中
ppppListAdd(ptemp);
//然后以这个子节点为开始重复这个方法
dg(ptemp);
}
}
}
//节点的定义类
public class pathPoint
{
//节点的id(对应着数据库的id)
public int pointId = 0;
//节点的所有子节点的pathPoint对象 (说明:这是一个递归自己的类结构 类似于树形)
public IList<pathPoint> ppList = new List<pathPoint>();
}
public abstract class DBHelper
{
//返回DataTable
public static DataTable QueryDataTable(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection("server=19216807;database=estar_infoSender;uid=sa;pwd=123456"))
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
daFill(ds, "ds");
cmdParametersClear();
}
catch (SystemDataSqlClientSqlException ex)
{
throw new Exception(exMessage);
}
return dsTables[0];
}
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (connState != ConnectionStateOpen)
connOpen();
cmdConnection = conn;
cmdCommandText = cmdText;
if (trans != null)
cmdTransaction = trans;
cmdCommandType = CommandTypeText;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmdParametersAdd(parm);
}
}
}
在SQL
SERVER
2000
中你可以先一些自定义函数,或一些存储过程,实现递归:
select
level,TypeName
from
ProductType
t
START
WITH
tParentID=0
CONNECT
BY
PRIOR
tProductTypeID=
tParentID;
SQL 数据库 实现递归查询的几种代码方法 表结构
ProductCategory
CategoryID Level ParentCategoryID
数据
T SQL
WITH CategoryTemp(CategoryID ParentCategoryID) 临时表用来保存查到的Category
(
SELECT CategoryID ParentCategoryID FROM ProductCategory WHERE ParentCategoryID<= 将所有的第一层查出来作为初始数据 需要查第几层或者哪个ParentCategoryID下面所有的 N层 把ParentCategoryID赋相关的值即可
UNION ALL 查询N层
SELECT pc CategoryID ParentCategoryID FROM ProductCategory pc
LEFT JOIN CategoryTemp ct ON pc ParentCategoryID=ct CategoryID
WHERE ParentCategoryID> 因为第一层前面已经查出来了 所以这里把第一层筛选掉
)
SELECT CategoryID ParentCategoryID FROM CategoryTemp
结果
如果把ParentCategoryID赋为 结果则为
实例
ID 是否为部门 部门名 上级ID y 部门 y 部门 n 张三 n 李二 y 部门 n 王五 y 部门3 n 小三 我想找询 ID 值为 下级的所有人员包括下级部门的所有人员
创建查询函数 create function f_id( @id int 要查询的id )returns @re table(id int level int) as begin declare @l int set @l= insert @re select id @l from 表 where 上级id=@id while @@rowcount> begin set @l=@l+ insert @re select a id @l from 表 a join @re b on a 上级id=b id and b level=@l end return end go
调用函数进行查询 select a from 表 a join f_id( ) b on a id=b id
联合查询
测试数据 create table 表(ID int 是否为部门 char( ) 部门名 varchar( ) 上级ID int) insert 表 select y 部门 union all select y 部门 union all select n 张三 union all select n 李二 union all select y 部门 union all select n 王五 union all select y 部门 union all select n 小三 go
创建查询函数 create function f_id( @id int 要查询的id )returns @re table(id int level int) as begin declare @l int set @l= insert @re select id @l from 表 where 上级id=@id while @@rowcount> begin set @l=@l+ insert @re select a id @l from 表 a join @re b on a 上级id=b id and b level=@l end return end go
调用函数进行查询 select a from 表 a join f_id( ) b on a id=b id go
删除测试 drop table 表 drop function f_id
/ 测试结果
ID 是否为部门 部门名 上级ID n 小三
lishixinzhi/Article/program/MySQL/201311/29557
以上就是关于sql用什么方法可以实现递归函数全部的内容,包括:sql用什么方法可以实现递归函数、树形结构获取路径 sql C#、sql语句中怎么实现递归查询等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)