PL / SQL:有条件的地方

时间:2013-04-23 19:29:16

标签: asp.net oracle plsql conditional where

我有以下情况:

CREATE OR REPLACE PROCEDURE GETINBOX
(
    inHasAttachments        IN int
)
AS

BEGIN

    SELECT M.MailId,
           M.SenderId,
           E.Emp_Name As "Sender",
           MI.RecipientId,
           M.Subject

    FROM MAIL M INNER JOIN MAILINBOX MI ON M.MailId = MI.MailId


    WHERE MI.RecipientId = '547' AND
          M.NotificationSelected = 'Y'

    IF inHasAttachments = '1' THEN
       AND M.Attachments = 'Y'
    END IF;


END GETINBOX;

是否可以根据参数的值为where子句添加条件?

    WHERE MI.RecipientId = '547' AND
          M.NotificationSelected = 'Y'

    IF inHasAttachments = '1' THEN
       AND M.Attachments = 'Y'
    END IF;

显然这是不允许的,但是可以在PL / SQL中以某种方式执行此操作吗? 我知道一种方法是复制查询并根据参数的值执行不同的查询,但我不想复制我的代码。

1 个答案:

答案 0 :(得分:3)

根据我的理解您的要求:如果参数inHasAttachments的值为1,那么您希望按M.Attachments = 'Y'进一步过滤,如果其值不是1那你不关心M.Attachments。这是条件MI.RecipientId = '547' AND M.NotificationSelected = 'Y'的补充。

你可以这样做:

SELECT M.MailId,
   M.SenderId,
   E.Emp_Name As "Sender",
   MI.RecipientId,
   M.Subject
FROM MAIL M INNER JOIN MAILINBOX MI ON M.MailId = MI.MailId
WHERE MI.RecipientId = '547' AND M.NotificationSelected = 'Y'
  AND (inHasAttachments <> '1' OR M.Attachments = 'Y')