About SQL with as loop usage

The WITH AS phrase, also called subquery factoring, is used to define an SQL fragment that will be used by the entire SQL statement. This statement is regarded as a common table expression (CTE). There is a limit to the loop SQL 2008 with, which can only be recursive up to 100 times. Let's test it below.

If I want to generate 1 to 200 rows of data

代码:with t as (
select 1 as id 
union all
select t.id+1 from t where t.id<200)
 select * from t   

An error is reported during runtime: The CTE restriction needs to be lifted using the recursion function,

with t as (
select 1 as id 
union all
select t.id+1 from t where t.id<200)
 select * from t 

option (maxrecursion 0) There is no problem with this implementation. 0 represents infinite, and can be changed to 1000 or 2000. The premise is that it is greater than the number of times you recurse, otherwise it will still report an error. Let's talk about using the custom value to cycle the specified value. The following is a SSRS report for demonstration. The excel effect chart is as follows. Now we need to make an SSRS report.

First: Circulate the names of the attendants and (attendance, work, and work), and then take out the credit card time.

with x as ------------ Define the cycle value
(select * from (values ​​(N 'Attendance'),
                                      (N 'To Work'),
                                      (N 'To Work')) as a (type1) ),
    y as (select distinct a.userid, b.name, b.BADGENUMBER
                 from attendance table a 
                 inner join usertable b on a.USERID = b.USERID,

z as (select * from x,y)

select * from z result


You can see that the three values ​​of attendance, work, and work have been circulated with each user,

    Second: Customize and specify the number of days that exist in a month of a certain year

Code like: date1 as

 (select convert (varchar (10), dateadd (DAY, t2.number, t1.day), 120) day from
(select @ date1 + '-' + @ date2 + ' -01  ' day) t1, 
(select number from MASTER. .spt_values ​​WHERE TYPE = 'P' AND number> = 0 and number <= 31) t2 
 where convert (varchar (10), dateadd (DAY, t2.number, t1.day), 120) like @ date1 + '-' + @ date2 + '%' 
    ) ----------- @ date1 is the specified year, @ date2 is the specified month, of course, you need to define the variable value in front, which is omitted here,

Third: Rank the punching time again, at http://blog.csdn.net/qyx0714/article/details/72683408, here is an introduction to taking punching data by punching time ranking, and finally finishing the SSRS chart as follows:



Published 22 original articles · praised 7 · 100,000+ views

Guess you like

Origin blog.csdn.net/qyx0714/article/details/72918801