比较一个列值与sql server中相同的数据列值?

时间:2014-02-18 12:39:32

标签: sql-server-2008 stored-procedures

ALTER proc [dbo].[K_RT_GetRatebasedonmeat]
    @partyname int,
    @meattype int
AS 
BEGIN
   SELECT  
      CASE WHEN PE.meattype <> (SELECT meattype 
                                FROM K_RT_PartyNameYearly 
                                WHERE partyname = @partyname) THEN 0  
           ELSE ISNULL(PE.rateperkg, 0) 
      END AS rateperkg 
   FROM
      K_RT_PartyNameYearly PE
   INNER JOIN 
      K_RT_PartyName PN ON PE.partysno = PN.sno 
   WHERE
      PE.partysno = @partyname 
      AND PE.meattype = @meattype
END

out put:

PE.partysno    PE.meattype   PE.rateperkg
36             3             150
36             2             125 
25             2             100   

如果我传递partysno = 36和meattype = 1,那么它将显示0,因为没有关于该partysno的肉类型1的数据

我是按照我的要求写的,但它不能正常工作。当我将partyname和meattype作为参数传递时,如果K_RT_PartyNameYearly此表不包含那个partyname的肉类型,那么我想显示0值。我怎么写这个?请帮帮我。

1 个答案:

答案 0 :(得分:0)

尝试这个......

ALTER proc [dbo].[K_RT_GetRatebasedonmeat]
    @partysno int,
    @meattype int
AS 
BEGIN
 if  exists
( SELECT 1 FROM K_RT_PartyNameYearly WHERE partysno = @partysno AND meattype = @meattype)
BEGIN
   SELECT 
   PE.partysno ,
   PE.meattype,
    PE.rateperkg 
   FROM
      K_RT_PartyNameYearly PE
   WHERE
      PE.partysno = @partysno AND PE.meattype = @meattype
END
ELSE
BEGIN

   SELECT distinct
    partysno partysno ,
    null   meattype,
    0 AS rateperkg 
   FROM
      K_RT_PartyNameYearly PE
   WHERE
      PE.partysno = @partysno
END
END