2011-09-13 2 views
0

저는 SQL Server 2008에서 초보자입니다. Proc.In이 Proc에는 2 개의 select 문이 있습니다. Proc를 실행하면 두 개의 테이블에서 결과를 얻을 수 있습니다. 그러나 나는이 단일 테이블에있는 반환에 원한다.단일 결과 테이블에서 두 개의 쿼리가 필요합니까?

내 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 

가능 얼마나 저를 제안하십시오?

미리 감사드립니다.

답변

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 ... 

그 결과는 열을해야합니다 Source, Name, Type , Ammount, AmmountTypePG_Type입니다. 여기서 Source은 첫 번째 행부터 1 행이고 두 번째 쿼리의 행은 2입니다.

+0

완료 .......... :) –

관련 문제