从一个表中获取多个值并使用从sql server中的存储过程中的另一个表中检索数据

时间:2012-01-17 04:35:16

标签: sql sql-server database sql-server-2008 stored-procedures

我需要从一个表中检索数据并使用它来使用存储过程从其他表中检索数据。

cart table
    CartId,
    PrdouctId -> should retrieve data from productinfo table 
    EmailId ->should Retrieve data from cart table that who many cart are register in this EmailId 
    cost,
    Quantity ,
    Ram -> contains HardWareId
    GraphicCard ->contains HardWareId
    ScreenSize ->contains HardWareId

ProductInfo Table
    ProductId,
    BrandlName,
    ModelName,
    Processor,

HardwareInfo table
    HardWareId,
    HardwareName,
    HarwareCost,

@EmailId将提供给存储过程

Select @ProductId =[productId],@Ram = [Ram] from cart where EmailId = @EmailId 
Select [BrandName],[ModelName] from ProductInfo where ProductId = @productId
select [HardwareName],[HardwareCost] from HardwareInfo where HardwareId = @Ram

BrandNameModelNameProcessorRamGraphicCardScreeSize将在列表视图中向用户显示。

我尝试这样做的方式是否正确?

1 个答案:

答案 0 :(得分:2)

看起来你想要这样的东西。

create procedure GetCartByEmailId
  @EmailId int
as  

select P.BrandName,
       P.ModelName,
       HR.HardwareName as RamName,
       HR.HardwareCost as RamCost,
       HG.HardwareName as GraphicCard,
       HG.HardwareCost as GraphicCardCost,
       HS.HardwareName as ScreenSize
from Cart as C
  inner join ProductInfo as P
    on C.ProductId = P.ProductId
  left outer join HardwareInfo as HR
    on C.Ram = HR.HardwareID
  left outer join HardwareInfo as HG
    on C.GraphicCard = HG.HardwareID
  left outer join HardwareInfo as HS
    on C.ScreenSize = HS.HardwareID
where C.EmailId = @EmailId