根据输入的值从数据库中选择ViewName

时间:2014-12-07 03:17:34

标签: sql-server sql-server-2008

我有一个名为广告的表格和两个名为子类别和子类别的表格,其中一些子类别没有子类别,而其他子类别。

因此,在Adverts表中,ChildCategoryId列可以为null,也可能有值,具体取决于此,我将返回要显示给用户的相关视图。

因此,如果childCategoryId列有一个值,我将关闭它并返回与ChildCategories表中的childCategoryId匹配的ViewName,如果它为null,则我加入SubCategory表并从那里返回ViewName。

如下所示我的代码看起来像他的

IF Exists(Select c.ViewName from Category.Child_Categories c
      inner join Advert.Adverts a on c.ChildCategoryId =a.ChildCatId
      where A.AdvertId = @ItemId and A.createdBy = @userID)
  Begin
      Select c.ViewName from Category.Child_Categories c
      inner join Advert.Adverts a on c.ChildCategoryId =a.ChildCatId
      where A.AdvertID = @ItemId and A.createdBy = @userID
  End
ELSE
  Begin
      Select s.ViewName from Category.Sub_Categories s
      inner join Advert.Adverts a on s.SubCategoryId =a.SubCatId
      where A.AdvertId = @ItemId and A.createdBy = @userID
  End

但对我来说,上面看起来有点OTT试图做这么简单的事情,因此我想我会问这里是否有其他人有更好的方法来做这件事

1 个答案:

答案 0 :(得分:1)

至少你可以通过查找相关的信息来简化IF条件(即,在NULL或NOT NULL上加入JOIN的ID字段)而不是自己进行JOIN:

IF EXISTS(SELECT *
          FROM  Advert.Adverts a
          WHERE a.AdvertId = @ItemId
          AND   a.CreatedBy = @UserID
          AND   a.ChildCatId IS NOT NULL)
BEGIN
  SELECT c.ViewName
  FROM Category.Child_Categories c
  INNER JOIN Advert.Adverts a
          ON c.ChildCategoryId = a.ChildCatId
  WHERE a.AdvertID = @ItemId
  AND   a.CreatedBy = @UserID;
END;
ELSE
BEGIN
  SELECT s.ViewName
  FROM Category.Sub_Categories s
  INNER JOIN Advert.Adverts a
          ON s.SubCategoryId = a.SubCatId
  WHERE a.AdvertId = @ItemId
  AND   a.CreatedBy = @UserID;
END;

或者,您可以通过捕获包含相关信息的两个字段,测试其中一个是NULL还是NOT NULL,然后针对一个表执行第二个查询,将其分解为更简单的查询。这可能会使优化器更容易正确使用索引。它仍然是2个查询,就像原始代码一样,但现在没有任何JOIN。

DECLARE @ChildCatId INT,
        @SubCatId INT;

SELECT @ChildCatId = a.ChildCatId,
       @SubCatId = a.SubCatId
FROM   Advert.Adverts a
WHERE  a.AdvertId = @ItemId
AND    a.CreatedBy = @UserID;

IF (@ChildCatId IS NOT NULL)
BEGIN
  SELECT c.ViewName
  FROM   Category.Child_Categories c
  WHERE  c.ChildCategoryId = @ChildCatId;
END
ELSE
BEGIN
  SELECT s.ViewName
  FROM   Category.Sub_Categories s
  WHERE  s.SubCategoryId = @SubCatId;
END;