2017-05-24 4 views
0

이 테이블에서 반환 된 값을 테이블에 삽입하려고합니다. 직접 '삽입 대상'이 작동하지 않습니다. 어떻게 내가이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 
+0

당신은 CTE AS (...) (등 1 열, 2 열) MYTABLE INTO INSERT 작업을해야 CTE' FROM 저쩌구 SELECT와 함께'테이블 데이터를 –

+0

를 제공하시기 바랍니다 수 있습니다. 당신이 그것을하려고 할 때 당신이 어떤 오류가 있습니까? – ZLK

답변

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 
0

당신의 cte가 작동하고 이미있는 table이있는 경우 열 [day],[date],[dayname] :

이것은 삽입물입니다. :

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