2011-12-22 28 views
0

由於此查詢的結果我有一個表:如何在下一個查詢中使用先前查詢的結果?

select i.id, o.[name] from Item i 
LEFT OUTER JOIN sys.objects o on o.[name]='I' + cast(i.id as nvarchar(20)) 
where o.name is not null 

enter image description here

現在我需要在接下來的查詢使用該表的結果:

select PriceListItem.ProductExternalId, @id.Id, @id.FriendlyName, @id.BriefWiki, 
    [PriceListItem].[ProductExternalDesc] 
from [@id] 
inner join [Product] on Product.ItemId = @name and Product.InstanceId = @id.ID 
inner join [PriceListItem] on Product.ID = PriceListItem.ProductId 

,而不是' @id'我應該使用名稱爲id的表格中的數據,而不是'@name'我應該使用名稱爲name的表中的數據

回答

1

由於您'再對SQL 2K8你可以使用一個CTE:

-- You may need a ; before WITH as in ;WITH 
WITH FirstQuery AS (
    select i.id, o.[name] from Item i 
    LEFT OUTER JOIN sys.objects o on o.[name]='I' + cast(i.id as nvarchar(20)) 
    where o.name is not null 
) 
select PriceListItem.ProductExternalId, 
     FQ.Id, 
     -- Neither of these are in your FirstQuery so you can not use them 
     -- @id.FriendlyName, @id.BriefWiki, 
     [PriceListItem].[ProductExternalDesc] 
from FirstQuery FQ 
    inner join [Product] on Product.ItemId = FQ.name 
         and Product.InstanceId = FQ.ID 
    inner join [PriceListItem] on Product.ID = PriceListItem.ProductId; 

單從查詢這很難告訴你如何計劃JOIN他們,但是這將允許您使用第一次查詢的在隨後的一個。

看起來您的第二個查詢中有一些語法錯誤 - @id.id

+0

我不知道如何使用第一個查詢在此腳本從哪裏我可以得到我的參數?你可以解釋嗎? – revolutionkpi 2011-12-22 15:14:06

+0

我沒有錯誤我只是改變了參數名稱,我不知道如何從第一個查詢中獲得 – revolutionkpi 2011-12-22 15:17:51

+0

「@ id」實際上是一個表變量嗎? – Yuck 2011-12-22 15:19:57

0
select i.id, o.[name] from Item i 
into @temp_table 
LEFT OUTER JOIN sys.objects o on o.[name]='I' + cast(i.id as nvarchar(20)) 
where o.name is not null 

現在,只要你想:)

1

標準SQL的方式,可以使用@temp_table,適用於大多數RDBMS

select PriceListItem.ProductExternalId, @id.Id, @id.FriendlyName, @id.BriefWiki, 
    [PriceListItem].[ProductExternalDesc] 
from 
    (
    select i.id, o.[name] from Item i 
    LEFT OUTER JOIN sys.objects o on o.[name]='I' + cast(i.id as nvarchar(20)) 
    where o.name is not null 
    ) 
    X 
    inner JOIN 
    [@id] ON X.id = @id.id --change here as needed 
    inner join [Product] on Product.ItemId = @name and Product.InstanceId = @id.ID 
    inner join [PriceListItem] on Product.ID = PriceListItem.ProductId* 
+0

從我讀過這個問題的角度來看,這個子查詢不應該被添加到查詢中,它應該去*而不是*'@ id'。 – 2011-12-26 02:22:29

相關問題