简体   繁体   中英

SQL: How to create a temp table and fill it with date within a select-from statement

I wish to create a temp table with 1 datetime column and then fill it with date(30 days before today). I wish to do all these in a select-from statement.

I could do it with a "WITH" loop as below prior to the select-from statement. However, I wish to do it within a select-from statement.

declare @endDate datetime
set @endDate = dateadd(day,-30,getdate())

with CTE_Table (
    Select dataDate = dateadd(day,-1,getdate()) from CTE_Table
    where datediff(day,dataDate,@endDate) < 0
)

select * from CTE_Table

Please help... :....(

You can use SELECT ... INTO .

BTW Your recursive CTE is invalid. A fixed version is below

DECLARE @endDate DATETIME

SET @endDate = dateadd(day, -30, getdate());

WITH CTE_Table(dataDate)
     AS (SELECT  dateadd(day, -1, getdate())
         UNION ALL
         SELECT dateadd(day, -1, dataDate)
         FROM   CTE_Table
         WHERE  datediff(day, dataDate, @endDate) < 0)
SELECT dataDate
INTO   #T
FROM   CTE_Table 

You could do:

CREATE TABLE #temptable
(
        DateColumn DATETIME
)

INSERT INTO #temptable
SELECT dataDate FROM CTE_Table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM