我已经创建了一个临时表,要填充记录。
这是我的查询:
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'。
上述查询中我在做什么错事?
答案 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
时,您应该列出所有要插入的列。