如何在 MSSQL 中基于带有变量声明的查询创建 table

How to create a table based on query with variable declaration in MSSQL

我想为漏斗查询创建一个 table,该查询有几天的声明 variable.If 我使用没有创建语句的查询,查询运行良好。当我尝试添加 select * into ..from 时出现两个错误:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'declare'. 
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near ')'. 

如何将包含日期声明的查询保存到新的 table

select * into tbl60D_AlertsFunnel from (
    declare @d date = getdate() - 60
    select sum(IP) AS IP ,sum(sentCount) sentCount, sum(readCount) readCount, sum(NumberOfOpensPerEmail) OpenNumber
    from (
    select COUNT(distinct CAST(sm.IP AS nvarchar(20))) as IP
      , count(distinct v.iditem) sentCount
      , MAX(cast(sm.OpenDate as date)) as OpenDateShort -- v.iditem is for sent, sm.OpenDate IS FOR OPEN
      ,count(cast(sm.OpenDate as date)) as NumberOfOpensPerEmail
      , count(distinct sm.iditem) readCount
    from fff.dbo.v_rep_MessageQueue v (nolock)
     left join [FF].[dbo].[tblMessageOpenedSMTP] sm
      on v.IdItem = sm.iditem
    -- and cast(sm.OpenDate as date)  > @d
    where v.IdMessageType = 20
     and V.DateScheduled > @d
     group by sm.IP
    ) d
    ) j

正如评论中指出的那样,您的查询应该是这样的

declare @d date = getdate() - 60 -- outside the select


select * into tbl60D_AlertsFunnel from (

    select sum(IP) AS IP ,sum(sentCount) sentCount, sum(readCount) readCount, sum(NumberOfOpensPerEmail) OpenNumber
    from (
    select COUNT(distinct CAST(sm.IP AS nvarchar(20))) as IP
      , count(distinct v.iditem) sentCount
      , MAX(cast(sm.OpenDate as date)) as OpenDateShort -- v.iditem is for sent, sm.OpenDate IS FOR OPEN
      ,count(cast(sm.OpenDate as date)) as NumberOfOpensPerEmail
      , count(distinct sm.iditem) readCount
    from fff.dbo.v_rep_MessageQueue v (nolock)
     left join [FF].[dbo].[tblMessageOpenedSMTP] sm
      on v.IdItem = sm.iditem
    -- and cast(sm.OpenDate as date)  > @d
    where v.IdMessageType = 20
     and V.DateScheduled > @d
     group by sm.IP
    ) d
    ) j

解释:

你的问题是虽然这个查询对你有效

declare @d date = getdate() - 60
    select sum(IP) AS IP ,sum(sentCount) sentCount, sum(readCount) readCount, sum(NumberOfOpensPerEmail) OpenNumber
    from (
    select COUNT(distinct CAST(sm.IP AS nvarchar(20))) as IP
      , count(distinct v.iditem) sentCount
      , MAX(cast(sm.OpenDate as date)) as OpenDateShort -- v.iditem is for sent, sm.OpenDate IS FOR OPEN
      ,count(cast(sm.OpenDate as date)) as NumberOfOpensPerEmail
      , count(distinct sm.iditem) readCount
    from fff.dbo.v_rep_MessageQueue v (nolock)
     left join [FF].[dbo].[tblMessageOpenedSMTP] sm
      on v.IdItem = sm.iditem
    -- and cast(sm.OpenDate as date)  > @d
    where v.IdMessageType = 20
     and V.DateScheduled > @d
     group by sm.IP
    ) d

您想将此作为子查询嵌套到 select into 语句,但无法将声明移到外面。