SQL存储过程使用IF-ELSE进行修改

时间:2016-04-26 16:05:25

标签: sql

到目前为止,这是我的存储过程

ALTER PROC [dbo].[getItems]
  (
    @EventId int,
    @OrgUserId int
  ) AS

BEGIN

DECLARE @BoardBookId int;
SET @BoardBookId = (SELECT bb.BoardbookId FROM Boardbook bb WHERE bb.ItemId = @EventId);

WITH PermissionDeniedAttachments AS
(
    SELECT bbi.CategoryItemId
    FROM BoardbookItem bbi 
    INNER JOIN CategoryItem ci ON ci.CategoryItemId = bbi.CategoryItemId
    WHERE bbi.BoardbookId = @BoardBookId AND bbi.CategoryItemId > 0 AND ci.catID NOT IN (SELECT catID from dbo.f_Categories(@OrgUserId))
)
SELECT 
    bbi.BoardbookId,
    bbi.BoardbookItemId,
    bbi.CategoryItemId,
    bbi.ChBy,
    bbi.ChDt,
    bbi.CrBy,
    bbi.CrDt,
    bbi.DeletedBy,
    bbi.DeletedDt,
    bbi.Description,
    bbi.Duration,
    bbi.ParentBoardbookItemId,
    bbi.SortOrder,
    bbi.Title,
    bbi.Resolutions,
    bbi.Presenter,
    bbi.BoardbookItemType,
    u1.Name_FirstLast as [ItemCreatedByName],
    u2.Name_FirstLast as [ItemChangedByName],
    CAST(CASE WHEN ci.deletedDt IS NULL THEN 0
                      ELSE 1 END AS BIT) AS Deleted,
    i.itemType as [DocType],
    ISNULL(ci.catID, 0) AS CatId,
    ISNULL(ci.itemID, 0) AS ItemId,
    d.docID as docId,
    d.docPages as DocPages,
    d.docPwdProtected AS HasPassword,
    bbi.BoardbookItemTypeCustom
from BoardbookItem bbi 
LEFT JOIN Users u1 on u1.UserName=bbi.CrBy
LEFT JOIN Users u2 on u2.UserName=bbi.ChBy
LEFT OUTER JOIN CategoryItem ci ON bbi.CategoryItemId IS NOT NULL AND bbi.CategoryItemId = ci.CategoryItemId
LEFT JOIN Item i ON ci.itemID = i.itemID
LEFT JOIN Documents d on d.docID = bbi.DocId
          where bbi.BoardbookId=@BoardBookId  AND bbi.DeletedDt IS NULL AND 
        (bbi.CategoryItemId IS NULL OR bbi.CategoryItemId NOT IN (Select CategoryItemId from PermissionDeniedAttachments)) 

现在我想要的是放一个var @submenuitem bit并测试它...... 所以,如果@submenuitem = 0我会得到与现在相同的效果, 但是如果@submenuitem = 1我还想再检查一下“的地方”。 'AND bbi.ParentBoardbookItemId='0'

似乎可以用IF ELSE语句来完成但不幸的是我无法以正确的方式完成

提前谢谢!

2 个答案:

答案 0 :(得分:6)

没有if... else声明,这绝对是可能的。

只需将其添加到where条件

即可
AND ((bbi.ParentBoardbookItemId='0' and @submenuitem = 1) or @submenuitem = 0)

它会像你描述的那样奏效。

答案 1 :(得分:1)

我建议您对WHERE子句进行简单的更改:

LEFT JOIN Documents d on d.docID = bbi.DocId
      where bbi.BoardbookId=@BoardBookId  AND bbi.DeletedDt IS NULL AND 
    (bbi.CategoryItemId IS NULL OR bbi.CategoryItemId NOT IN (Select CategoryItemId from PermissionDeniedAttachments)
      AND (@submenuitem = 0 OR bbi.ParentBoardbookItemId='0')