如何在下一个查询中使用上一个查询的结果?

时间:2011-12-22 15:07:12

标签: c# sql-server sql-server-2008

作为此查询的结果,我有一个表:

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'我应该使用name = id的表中的数据,而不是'@name'我应该使用name = name

表中的数据

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

标准SQL方式,适用于大多数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*

答案 2 :(得分: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

现在您可以根据需要使用@temp_table:)