SQL 中的尖括号">"自动转成>,SQL递归简单写法
2011-12-26 21:11
423 查看
在写一句SQL的时候,发现有时SQL会自动把> 转成>
代码如下:
这是原来的传统方法 ,FUNCTION
返回结果:你->说->我->是->乖->猪
但发现出来的结果是:gt;你->说->我->是->乖->猪
没找到是什么原因,也不管了,就这么着吧,直接用Replace
出来的答案是对了,但为什么一定要Replace呢?
如果你有更好的办法,请告知,谢谢
如果这个NID是不连续的,例如,如下的数据,
就不能直接用上面的代码了,而要先根据NID获取,可以利用SQL2005以上版本的WITH,实现递归
代码如下:
if object_id('t_001') >0 drop table t_001 create table t_001 (id int ,val varchar(100),nid int) insert into t_001 select 0,'我',1 union select 1,'爱',2 union select 2,'听',3 union select 3,'你',4 union select 4,'说',5 union select 5,'我',6 union select 6,'是',7 union select 7,'乖',8 union select 8,'猪',9 union select 9,'猪',NULL select * from t_001 if object_id('f_t_001')>0 drop function f_t_001 go create function f_t_001 ( @id int,@nid int) returns varchar(500) as begin declare @tval varchar(20),@tid int,@tnid int select @tval=val,@tid=id ,@tnid=nid from t_001 where id=@id return case when @id=@nid or isnull(@tnid,'')='' then isnull(@tval,'') else isnull(@tval+'->'+dbo.f_t_001(@tnid,@nid),'') end end go select dbo.f_t_001 (3,8)
这是原来的传统方法 ,FUNCTION
返回结果:你->说->我->是->乖->猪
select stuff( (select '->',val+'' from t_001 where id between 3 and 8 for xml path('')) ,1,2,'')
但发现出来的结果是:gt;你->说->我->是->乖->猪
没找到是什么原因,也不管了,就这么着吧,直接用Replace
select stuff( Replace( (select '->' +'',val+'' from t_001 where id between 3 and 8 for xml path('')) ,'>','>') ,1,2,'')
出来的答案是对了,但为什么一定要Replace呢?
如果你有更好的办法,请告知,谢谢
如果这个NID是不连续的,例如,如下的数据,
if object_id('t_001') >0 drop table t_001 create table t_001 (id int ,val varchar(100),nid int) insert into t_001 select 0,'我',1 union select 1,'爱',3 union select 2,'听',4 union select 3,'你',2 union select 4,'说',5 union select 5,'我',6 union select 6,'是',7 union select 7,'乖',8 union select 8,'猪',9 union select 9,'猪',NULL
就不能直接用上面的代码了,而要先根据NID获取,可以利用SQL2005以上版本的WITH,实现递归
with ctea (id,val,nid,tlevel) as ( select id,val,nid,0 as tlevel from t_001 where id = 0 union all select t.id,t.val,t.nid,e.tlevel+1 from t_001 t inner join ctea e on e.nid = t.id ) select * from ctea order by tlevel
相关文章推荐
- <input type="file" name="filePath" />最简单的解决方法
- mybatis在<if>中传入一个简单类型参数的两种写法。
- Oracle与SQL-Server数据库SQL"树查询"对比[按照父子节点关系递归拼接]
- 简单代码autocomplete="off"实现禁用input输入框的自动提示功能
- IE10打开网页后,自动设置浏览器模式为“IE10兼容性视图”,我添加了 <meta http-equiv="X-UA-Compatible" content="IE=8">只修改了文档模式,请问如何
- 有时头文件引用为什要用双引号("")而不是尖括号呢"<>"?
- 递归字符串翻转"abc"->"cba"
- 页面对json返回自动result:<pre style="word-wrap: break-word; white-space: pre-wrap;">{"flag":"true"}</pre>问题
- 我看'工厂模式'--->"简单工厂、工厂方法、抽象工厂"
- PL\SQL 打开时出现"动态执行表不可访问,本会话的自动统计被禁止"
- hive 非等值连接sql写法-2<转>
- 利用"SQL"语句自动生成序号的两种方式
- JSP+JavaBean不能使用jsp:setProperty name="BeanName" property="*"/>来自动提交日期表单
- 当php内置函数需要以字符串格式调用&quot;$this-&gt;fun名&quot;类内函数时写法
- PL\SQL 打开时出现"动态执行表不可访问,本会话的自动统计被禁止"错误解决
- 今天的c++练习代码———>"欧几里德算法+函数的递归解决求2个整数的最大公约数"
- 关于spring中<context:component-scan base-package="" />写法
- PL\SQL 打开时出现"动态执行表不可访问,本会话的自动统计被禁止"
- 【转】关于"递归树形查询SQL"的好帖
- Mysql C API 使用(二)简单的sql语句执行&dbvisualizer设置自动提示