从common_table_expression将值插入表中

时间:2017-05-24 05:46:31

标签: sql-server common-table-expression

我想将从此表返回的值插入表中。直接'插入'不起作用。我该怎么做

 declare @WeakNumber int =3

DECLARE @month AS INT = DATEPART(m, DATEADD(m, -1, getdate()))    --last month 
DECLARE @Year AS INT = DATEPART(yyyy, DATEADD(m, -1, getdate()))  -- last month's year
DECLARE @dayFrom AS INT 
DECLARE @dayTo AS INT 

SET @dayFrom =(CASE @WeakNumber WHEN 2 THEN 8
                                    WHEN 3 THEN 15  
                   END)

SET @dayTo =(CASE @WeakNumber WHEN 2 THEN 14
                                    WHEN 3 THEN 21

                   END)



;WITH N(N)AS 
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT N day,datefromparts(@year,@month,N) date , DATENAME(dw,datefromparts(@year,@month,N)) dayname
FROM tally
WHERE N <= day(EOMONTH(datefromparts(@year,@month,1)))

 AND DATEPART(dw,datefromparts(@year,@month,N)) = 5        -- Thursday
 AND DATEPART(d,datefromparts(@year,@month,N)) BETWEEN  @dayFrom AND @dayTo 

返回的表数据如下所示

day date       dayname
20  2017-04-20  Thursday

2 个答案:

答案 0 :(得分:1)

就这么简单:

DECLARE @WeakNumber INT =3 
DECLARE @month AS INT = Datepart(m, Dateadd(m, -1, Getdate())) --last month  
DECLARE @Year AS INT = Datepart(yyyy, Dateadd(m, -1, Getdate())) -- last month's year 
DECLARE @dayFrom AS INT 
DECLARE @dayTo AS INT 

SET @dayFrom =( CASE @WeakNumber 
                  WHEN 2 THEN 8 
                  WHEN 3 THEN 15 
                END ) 
SET @dayTo =( CASE @WeakNumber 
                WHEN 2 THEN 14 
                WHEN 3 THEN 21 
              END ) 

DECLARE @required TABLE 
  ( 
     [day]     INT, 
     [year]    CHAR(20), 
     [dayname] CHAR(20) 
  ); 

WITH n(n) 
     AS (SELECT 1 
         FROM  (VALUES(1), 
                      (1), 
                      (1), 
                      (1), 
                      (1), 
                      (1))M(n)), 
     tally(n) 
     AS (SELECT Row_number() 
                  OVER( 
                    ORDER BY n.n) 
         FROM   n, 
                n a) 
INSERT INTO @required 
SELECT n                                             day, 
       Datefromparts(@year, @month, n)               date, 
       Datename(dw, Datefromparts(@year, @month, n)) dayname 
FROM   tally 
WHERE  n <= Day(Eomonth(Datefromparts(@year, @month, 1))) 
       AND Datepart(dw, Datefromparts(@year, @month, n)) = 5 -- Thursday 
       AND Datepart(d, Datefromparts(@year, @month, n)) BETWEEN 
           @dayFrom AND @dayTo 

SELECT * 
FROM   @required 

答案 1 :(得分:0)

如果您的cte正常运行且您已table[day],[date],[dayname],那么

这是插入:

 Insert into YOURTABLE ([day],[date],[dayname]) 
 select [day],[date],[dayname] from N