SQL - 根据条件从多个源中的一个获取值

时间:2013-06-20 11:30:54

标签: sql

我有以下表结构:

TransactionTable

transactID  TBarcode   Ecode  PAICID  status
1            1234      E001    1         0
2            4567      E002    2         1

UserMasterTable

Uid   Uname Ecode
1      jas   E001
2      biju   E002

EmployeeMasterTable

Ecode        Ename
E001         Jaseem
E002         bijeesh

TransactionTable.PAICDUserMasterTable.Uid是相同的。

我在TBarcde上搜索(我的意思是像WHERE Tbarcode = 1234这样的条件)

如果status为0,那么我希望相应的EnameTransactionTable.Ecode相关。

如果status为1,那么我想从相应的Ename PAICID的{​​{1}}中取出UserMasterTable.Ecode

我如何为此编写存储过程?

2 个答案:

答案 0 :(得分:1)

您不需要存储过程。以下查询将满足您的需求:

直接通过TransactionTable加入EmployeeMasterTable并通过UserMasterTable,然后根据状态标准从正确的加入员工表中选择Ename

SELECT 
    t.*,
    CASE 
        WHEN t.status = 0 
            THEN e0.Ename 
        ELSE e1.Ename 
    END AS Ename
FROM TransactionTable AS t
LEFT JOIN EmployeeMasterTable AS e0
    ON t.Ecode = e1.Ecode
LEFT JOIN UserMasterTable AS u
    ON t.PAICID = u.Uid
LEFT JOIN EmployeeMasterTable AS e1
    ON u.Ecode = e1.Ecode
WHERE TBarcode = 1234

如果确实在存储过程中需要它,请参考DBMS的文档以了解如何执行此操作。它可能类似于

CREATE PROCEDURE MyProcedure (IN iTBarcode INT)
BEGIN
    SELECT 
        t.*,
        CASE 
            WHEN t.status = 0 
                THEN e0.Ename 
            ELSE e1.Ename 
        END AS Ename
    FROM TransactionTable AS t
    LEFT JOIN EmployeeMasterTable AS e0
        ON t.Ecode = e1.Ecode
    LEFT JOIN UserMasterTable AS u
        ON t.PAICID = u.Uid
    LEFT JOIN EmployeeMasterTable AS e1
        ON u.Ecode = e1.Ecode
    WHERE TBarcode = iTBarcode
END

答案 1 :(得分:1)

您需要LEFT JOIN到UsermasterTable,将状态置于连接条件,然后您可以使用COALESCE INNER JOIN EmployeeMasterTable,因此说明UserMasterTable中有匹配时使用ECode,否则使用Ecode来自TransactionTable

SELECT  TransactionTable.TransactID,
        TransactionTable.TBarCode,
        TransactionTable.ECode,
        TransactionTable.PAICID,
        TransactionTable.Status,
        EmployeeMasterTable.Ename
FROM    TransactionTable
        LEFT JOIN UserMasterTable
            ON UserMasterTable.ECode = TransactionTable.ECode
            AND TransactionTable.Status = 0
        INNER JOIN EmployeeMasterTable
            ON EmployeeMasterTable.ECode = COALESCE(UserMasterTable.ECode, TransactionTable.ECode)
WHERE   TransactionTable.BarCode = '1234';