如何在SQL中使用; with命令将记录插入到temptable中?

时间:2019-06-05 02:17:57

标签: sql sql-server

我已经创建了一个临时表,要填充记录。

这是我的查询:

create table #temp(companysitetankid int, [SourceGradeName] varchar(50), SiteCode varchar(50));

;with cst  as (
    select companysitetankid,[SourceGradeName], SiteCode,
           row_number() over (partition by [SourceGradeName] order by [TankNumber] ) rn
    from [DataManagement_DB].[dbo].[CompanySiteTank]  where CompanyCode='Aaaa'
 )
 select * from cst where  rn >1

 insert into #temp
 select companysitetankid,[SourceGradeName], SiteCode from cst  

我在这里得到表cst无效。

  

无效的对象名称'cst'。

上述查询中我在做什么错事?

2 个答案:

答案 0 :(得分:3)

一旦cst语句中使用了别名为SELECT的CTE,就无法再次使用它。这可能就是您打算做的:

WITH cst AS (
    SELECT companysitetankid, [SourceGradeName], SiteCode,
       ROW_NUMBER() OVER (PARTITION BY [SourceGradeName] ORDER BY [TankNumber]) rn
    FROM [DataManagement_DB].[dbo].[CompanySiteTank]
    WHERE CompanyCode = 'Aaaa'
)

INSERT INTO #temp
SELECT companysitetankid, [SourceGradeName], SiteCode
FROM cst
WHERE rn > 1;

如果您确实需要运行该select来检查返回的内容,请在侧面运行它,但是在插入中实际使用它时将其删除。

答案 1 :(得分:1)

您可以在一条语句中完成所有操作:

with cst as (
      select companysitetankid, [SourceGradeName], SiteCode,
             row_number() over (partition by [SourceGradeName] order by [TankNumber] ) rn
      from [DataManagement_DB].[dbo].[CompanySiteTank]
      where CompanyCode='Aaaa'
     )
insert into #temp
    select companysitetankid,[SourceGradeName], SiteCode 
    from cst  
    where rn > 1;

注意:使用insert时,您应该列出所有要插入的列。