SQL Server 自定义函数 返回树结构函数
生活随笔
收集整理的這篇文章主要介紹了
SQL Server 自定义函数 返回树结构函数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
數(shù)據(jù)庫(kù)結(jié)構(gòu):
表內(nèi)的數(shù)據(jù):
自定義函數(shù): 遞歸查出 樹(shù)下所有節(jié)點(diǎn) ,參數(shù)是 父id
create function sss(@id as int)returns @t table(id int not null,name int not null,pid int null)asbegindeclare @lay as int;insert into @t select * from tree where pid =@id;select @lay = min(id) from tree where pid =@id; --第一次 @lay=5while @lay is not nullbegininsert into @t select * from sss(@lay);select @lay=min(id) from treewhere id>@lay and pid=@idendreturn;endgo.net代碼: string cons = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();using (SqlConnection con=new SqlConnection(cons)){if (con.State==ConnectionState.Closed){con.Open();}string sql = "select * from sss(@id)";SqlCommand cmd = new SqlCommand(sql,con);cmd.CommandType = CommandType.Text;cmd.Parameters.Add(new SqlParameter("@id", DbType.Int32)).Value = 4;cmd.Parameters.Add("@re",DbType.String);cmd.Parameters["@re"].Direction = ParameterDirection.ReturnValue;SqlDataReader dr = cmd.ExecuteReader();while (dr.Read()){int i = 0;Response.Write(dr[0].ToString() + "\t\t\t" +dr[1].ToString() +"\t\t\t"+ dr[2].ToString() + "</br>");i++;}con.Close();
?}
實(shí)現(xiàn)的效果如下:
轉(zhuǎn)載于:https://www.cnblogs.com/lgzh3/archive/2012/11/01/2749988.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的SQL Server 自定义函数 返回树结构函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java面试之简述一下 Java 垃圾回
- 下一篇: oracle 实时查询最耗CPU资源的S