1

我有以下表结构:

事务表

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

用户主表

Uid   Uname Ecode
1      jas   E001
2      biju   E002

员工主表

Ecode        Ename
E001         Jaseem
E002         bijeesh

TransactionTable.PAICD并且UserMasterTable.Uid是相同的。

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

如果status是 0 那么我想要EnameTransactionTable.Ecode.

如果status是 1 那么我想Ename从对应的PAICIDEname 中获取UserMasterTable.Ecode.

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

4

2 回答 2

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
于 2013-06-20T11:39:39.823 回答
1

您需要到LEFT JOINUsermasterTable,将状态置于连接条件中,然后您可以使用 COALESCE INNER JOIN EmployeeMasterTable,因此当 UserMasterTable 中存在匹配项时,请使用其中的 ECode,否则使用 TransactionTable 中的 Ecode

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';
于 2013-06-20T11:40:07.473 回答