单个结果表中的两个查询?

时间:2011-09-13 13:40:43

标签: sql-server-2005 stored-procedures

我是SQL Server 2008中的新手。有一个Proc.In这个Proc,我有两个select语句。当我执行我的Proc时,我会在两个表中得到结果,我接受了。但我想在单表中回归。

My Proc -

 ALTER PROC [GetPaymentGateway]  
 @CompanyID VARCHAR(3),  
 @ChannelType varchar(15)=null
AS  

IF @ChannelType='BODC' OR @ChannelType='BO-DC'  
BEGIN
    SELECT [card_name], [card_type], [BODC_Amount], [BODC_Amount_Type], PGM.PG_Type FROM credit_card_master CCM
    INNER JOIN PaymentGateway_master PGM
    ON PGM.payment_gateway_code = CCM.payment_gateway_code  
    WHERE CCM.company_id = @CompanyID and CCM.disabled = '1'

    SELECT PGM.Payment_Gateway_Name, PGNBC.BODC_Charge_Amt, PGNBC.BODC_Charge_type, PGM.PG_Type 
    FROM PG_NetBanking_Charges PGNBC
    INNER JOIN PaymentGateway_master PGM
    ON PGM.payment_gateway_code = PGNBC.payment_gateway_code
    WHERE PGNBC.company_id = @CompanyID
END

IF @ChannelType='B2C' OR @ChannelType='ONLINE-DC'  
BEGIN
    SELECT [card_name], [card_type], [charge_amount], [B2C_Amount_type], PGM.PG_Type FROM credit_card_master CCM
    INNER JOIN PaymentGateway_master PGM
    ON PGM.payment_gateway_code = CCM.payment_gateway_code 
    WHERE CCM.company_id = @CompanyID and CCM.disabled = '1' 

    SELECT PGM.Payment_Gateway_Name, PGNBC.Online_DC_Charge_Amt, PGNBC.Online_DC_Charge_type, PGM.PG_Type 
    FROM PG_NetBanking_Charges PGNBC
    INNER JOIN PaymentGateway_master PGM
    ON PGM.payment_gateway_code = PGNBC.payment_gateway_code
    WHERE PGNBC.company_id = @CompanyID
END 

请建议我怎么可能?

提前致谢。

1 个答案:

答案 0 :(得分:2)

要在一个表中组合两个查询,您需要UNION操作。这需要两个结果集,基本上将它们粘在一起。
Union几乎没有限制,最重要的是查询必须具有相同的列数。

在您的查询中,您选择了不同的列数,credit_card_master个查询各有5列,PG_NetBanking_Charges个查询各有4列。

从我所看到的情况来看,我猜第一个查询中的card_type列在第二个查询中没有等效项,因此您可以将第二个查询重写为:

SELECT card_name, card_type, charge_amount, B2C_Amount_type, PGM.PG_Type 
  FROM ...
  WHERE ...
UNION
SELECT PGM.Payment_Gateway_Name, null, PGNBC.Online_DC_Charge_Amt,
       PGNBC.Online_DC_Charge_type, PGM.PG_Type
  FROM ...
  WHERE ...

另请注意,结果集中的列将采用第一个查询中列的名称,因此您可能希望添加列别名以获取列的更有意义/通用名称。此外,我通常添加一个“源”列,使我能够跟踪联合中行的来源,因此我的最终查询将如下所示:

SELECT 1 as Source, card_name as Name, card_type as Type, 
       charge_amount as Ammount, B2C_Amount_type as AmmountType,
       PGM.PG_Type as PG_Type
  FROM ...
  WHERE ...
UNION
SELECT 2, PGM.Payment_Gateway_Name, null, PGNBC.Online_DC_Charge_Amt,
       PGNBC.Online_DC_Charge_type, PGM.PG_Type
  FROM ...
  WHERE ...

,结果将包含SourceNameTypeAmmountAmmountTypePG_Type列,其中{{1对于第一个行中的行将为1,对于第二个查询中的行将为2。