declare @startDay smalldatetime ='2013-01-01' ;with cte as( select @startDay as d union all select DATEADD(d,1,d) as d from cte where d<'2019-05-01') select * from cte --设置循环次数,0为无限制OPTION(MAXRECURSION 0)…
WITH cte_name AS ( --Anchor member is defined ' UNION ALL --Recursive member is defined referencing cte_name select a.PCY_Name,a.PCY_ID,a.PCY_Parent, a.PCY_Code,a.PCY_Status from PB_Code_MaterType a inner join cte_name c on a.PCY_Parent=c.PCY_ID ) --…
)) INSERT INTO @t SELECT 'AAA,BBB,CCC' SELECT * FROM @t ;WITH mycte AS ( ,mend,num FROM @t UNION ALL ,num FROM mycte WHERE mend<=LEN(sentence) ) ),,,'') sentence FROM mycte 如果由excel中直接复制过来的,可能在没一个项前会有换行符,替换方法为 replace char(13) + char(10) 更简单的可以转换为xm…
今天用到了sql的递归查询.递归查询是CTE语句with xx as(....)实现的. 假如表Category数据如下. 我们想查找机枪这个子分类极其层次关系(通过子节点,查询所有层级节点).以下是查询语句 WITH tt AS ( SELECT CategoryId,Name,Parent,0 level FROM dbo.Category WHERE CategoryId=15 --定位点成员 UNION ALL SELECT c.CategoryId,c.Name,c.Parent,tt…
CTE是如何进行递归的?产生递归的条件有三个,分别是 初始值 自身调用自身 结束递归的条件 1,示例代码 ;with cte as ( as jd union all as jd from cte ) select * from cte 查询结果如下 2,递归过程分析 2.1 初始值 select 1 as id, 1 as jd 提供初始值,CTE中的值只有这一个. 2.2 第一次递归调用 select id +1 as id ,jd+2 as jdfrom ctewhere id<10 在第…
每个地区递归层级可能不一致,数据表(table)存放最小层级地区 area --地区层级表 id name f_id leve 1 中国 0 1 2 湖北 1 2 3 武汉 2 3 ... --测试数据 with area(id,"name",f_id,leve) as ( ,, union all ,, union all ,, union all ,, union all ,, union all ,, union all ,, union all ,, union all ,,…
CASE函数 作用: 可以将查询结果集的某一列的字段值进行替换 它可以生成一个新列 相当于switch...case和 if..else 使用语法: case 表达式/字段 when 值 then 自定义值 else end as 别名 when 值 then:可以理解为当某个字段为某个值的时候,然后就返回自定义值将结果集的字段值进行替换 else:如果上面的when都不满足就执行else结果 常用用法一(case后面有字段或者表达式): when关键字后面写固定值 case关键字后面如果有…
最近学习了一下SQL的分页查询,总结了以下几种方法. 首先建立了一个表,随意插入的一些测试数据,表结构和数据如下图: 现在假设我们要做的是每页5条数据,而现在我们要取第三页的数据.(数据太少,就每页5条了) 方法一: * from [StuDB].[dbo].[ScoreInfo] where [SID] not in ( [SID] from [StuDB].[dbo].[ScoreInfo] order by [SID]) order by [SID] 结果: 此方法是先取出前10条的SID…
where in 的参数化查询实现 首先说一下我们常用的办法,直接拼SQL实现,一般情况下都能满足需要 string userIds = "1,2,3,4"; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = string…
转载至:http://www.cnblogs.com/lzrabbit/archive/2012/04/22/2465313.html 文章导读 拼SQL实现where in查询 使用CHARINDEX或like实现where in 参数化 使用exec动态执行SQl实现where in 参数化 为每一个参数生成一个参数实现where in 参数化 使用临时表实现where in 参数化 like参数化查询 xml和DataTable传参 身为一名小小的程序猿,在日常开发中不可以避免的要和wh…
sql 树 递归 with SubQuery(No,Name,ParentNo) as ( ' union all select A.No,A.Name,A.ParentNo from [Port_Dept] A inner join SubQuery B on A.No = B.ParentNo ) select * from SubQuery…