1>cte语法
1.1>基础语句和递归语句中必须有字段
1.2>最后只能跟一条查询语句
1.3>字符串拼接,要将拼接的字段转成字符串类型,cast(fieldName as nvarchar(max))
with cte[(field1,field2,...)] as ( --基础语句,必须有字段 select field1,field2,... from tableName union all --递归语句,必须有字段 select field1,field2,... from tableName a,cte b where a.fieldName=b.fieldName ) select * from cte;--只能跟一条查询语句
2>cte 实例,添加一些拼接的字符串
with dept as ( select DEPTNAME as DEPTNAME,DEPTID,PDEPTID,cast(DEPTNAME as nvarchar(max)) as name from DEPARTMENT where DEPARTMENT.DEPTNAME=‘信息中心‘ union all select a.DEPTNAME,a.DEPTID,a.PDEPTID,cast(a.DEPTNAME+‘\‘+b.name as nvarchar(max)) as name from DEPARTMENT a inner join dept b on a.DEPTID=b.PDEPTID ) select * from dept where DEPTNAME=‘信息中心‘;
时间: 2024-10-20 18:13:05