【发布时间】:2013-02-22 05:49:18
【问题描述】:
这是我的查询不正确:
;With normal As
(
Select ROW_NUMBER() Over (Order by RecordingDateTime) as RowNum,
DocumentID,
CreatedByAccountID,
JurisdictionID,
InstrumentID
-- Cast(InstrumentID as decimal(18)) as InstrumentID
From Documents Where RecordingDateTime IS NOT NULL
)
Select Top 1 @PreviousInstrumentID = InstrumentID,
@PreviousDocumentID = DocumentID,
@PreviousCreatedByAccountID = CreatedByAccountID,
@PreviousBelongsToJurisdictionID = JurisdictionID
From normal
Where RowNum = @RowNum - 1
Select Top 1 @NextInstrumentID = InstrumentID,
@NextDocumentID = DocumentID,
@NextCreatedByAccountID = CreatedByAccountID,
@NextBelongsToJurisdictionID = JurisdictionID
From normal
Where RowNum = @RowNum + 1
我希望两个 select 语句都在 CTE 的上下文中。我如何做到这一点?
【问题讨论】:
-
你不能这样做。 CTE 仅适用于一个语句。如果您需要保留结果 - 您需要将其放入临时表(或表变量)中,然后针对该结果运行您的两个语句
-
@marc_s:谢谢!表变量不会低效吗?我目前在表中有 10 万条记录,并且会随着时间的推移而增加。请提出您的想法。
-
这个查询的输出是如何消费的?你真的需要那些变量赋值吗?
-
是的,否则我不会编写查询。
-
表变量适用于少数几行 - 但如果有 100K,我会选择临时表
标签: sql sql-server-2008 tsql common-table-expression