2012-10-10 160 views
-4
USE [cms] 
GO 
/****** Object: StoredProcedure [dbo].[SpGetRelatedProducts] Script Date: 10/10/2012 14:35:39 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER proc [dbo].[SpGetRelatedProducts](@pid int) 
AS 
DECLARE @subcate int; 
select subcate_id as subcate from product where [email protected] 
SELECT * 
FROM product 
where [email protected] 




exec SpGetRelatedProducts 2 

以上sql查詢不能按要求正常工作。sql查詢不能正常工作

我希望只有那些產品具有subcatid =(subcatid給定pid)的產品詳細信息。

有2個問題

  1. 只有1個輸出應該出現,而不是2

  2. 第二輸出工作不正常

+0

存儲過程是否與這個問題有關? – Jodrell

+0

你需要的是'SELECT fieldName INTO @variableName ...' –

+0

@GermannArlington,'int'不是表變量。 – Jodrell

回答

1

@subcate參數未分配:

select @subcate = subcate_id from product where [email protected] 

select * from product where product.subcate_id = @subcate 
2

試試這個:

alter proc [dbo].[SpGetRelatedProducts](@pid int) 
as 

select * 
from product as p1 
where p1.subcate_id in (
         select p2.subcate_id 
         from product as p2 
         where p2.pid = @pid 
         ) 
+0

很好用 現在它的工作............- :) – user1734269

+0

當然,如果有不同'subcate_id'的行共享一個'pid',那麼這個和我的答案都會給出錯誤的結果。 – Jodrell

0

你不妨做這一切在一個聲明中

SELECT 
       P1.* 
    FROM 
      product P1 
     JOIN 
      prodcut P2 
       ON p1.subcate_id = p2.subcate_id 
    WHERE 
     P2.pid = @pid 

,而不是擔心設置中間變量。