[英]SQL combine WITH clause and Cursor
如何在一個查詢中使用聲明的參數 , WITH子句和游標
declare @TOP10 table (Cat Nvarchar(max),SubGUID uniqueidentifier)
declare @Sub uniqueidentifier
declare GUID_Cursor cursor FOR
(select SubGUID from dbo.Sub with(nolock) where year=2016)
;
with [MyTable] as
(
Select SubGUID, color from dbo.Cars with(nolock) where color ='blue'
)
open GUID_Cursor
fetch next from GUID_Cursor into @Sub
while @@FETCH_STATUS=0
begin
insert into @TOP10 (Cat,SubGUID)
select color,SubGUID from [MyTable]
where SubGUID=@Sub
fetch next from GUID_Cursor into @Sub
end
close GUID_Cursor
deallocate GUID_Cursor
select * from @TOP10
我只是找不到使用WITH子句后打開游標的方法。
誰能幫我?
好吧,除了代碼的邏輯(對我而言-根本不需要游標),您應該將CTE聲明移到更靠近使用它的地方。
;with [MyTable] as
(
Select SubGUID, color from dbo.Cars with(nolock) where color ='blue'
)
insert into @TOP10 (Cat,SubGUID)
select color,SubGUID from [MyTable]
where SubGUID=@Sub
但實際上,您的所有代碼都可以替換為:
declare @TOP10 table (Cat Nvarchar(max),SubGUID uniqueidentifier)
insert into @TOP10 (Cat,SubGUID)
select color,SubGUID
from dbo.Cars with(nolock)
where
color ='blue'
and SubGUID in (select SubGUID from dbo.Sub with(nolock) where year=2016)
select * from @TOP10
我同意@AndyKorneyev,但出於實驗目的:
declare @crTest CURSOR,
@name VARCHAR(1000),
@type VARCHAR(1000)
set @crTest = CURSOR FAST_FORWARD FOR
WITH cteObjs AS (
SELECT TOP 10 NAME, type
FROM sys.objects o
)
select name, type
from cteObjs
OPEN @crTest
FETCH NEXT FROM @crTest
INTO @name, @type
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @name
PRINT @type
FETCH NEXT FROM @crTest
INTO @name, @type
END
CLOSE @crTest
DEALLOCATE @crTest
不想重復上述片段,但請注意, WITH
子句結果集必須直接在其結尾處進行處理。
與@tableVar不同,cte返回的結果集的范圍在完整批處理中無效,因此必須緊隨其后的是SELECT,INSERT,UPDATE或DELETE語句 。 (有關詳細信息和示例,請參閱: https : //msdn.microsoft.com/zh-cn/library/ms175972.aspx或遵循其他答案之一)。
例如
--> declare var:
declare @tableVar table (colOne int, colTwo nvarchar(30)
);
--> use cte:
with preOne as(select carId, color from pcUser with (nolock)
)
--> directly followed by insert:
insert into @tableVar(userId, logInName)
select colOne, colTwo from @tableVar;
--> use var in cursor or anywhere else in the batch
雖然我不確定您的目標是什么,但也許短暫的加入可以達到目的:
select a.[SubGUID]
from [dbo].[Sub] as a with (nolock)
inner join [dbo].[Cars] as b with (nolock) on a.[SubGUID] = b.[SubGUID]
where a.[year] = 2016 and b.[color] = 'blue';
最后,我使用了諸如#TOP10之類的臨時標簽。 我在查詢后刪除了它。 一旦我擺脫了with [MyTable] as
我的參數就不再有問題了。
謝謝大家
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.