开发者

TSQL: If statement inside a With statement

开发者 https://www.devze.com 2023-01-29 16:31 出处:网络
My problem is that I want to merge two SPs in one. the skeleton of the resulting sp is开发者_如何学编程:

My problem is that I want to merge two SPs in one. the skeleton of the resulting sp is开发者_如何学编程:

 with Paging(RowNo, ID, Name, Description, LengthSeconds, Rating, Url, ThumbnailFileName, AddedAt) AS
    (
     (if(@SortType is null)
      begin
         ... select ... 
      end
      else 
      begin
        ... select...
      end
    )

   select * from Paging ... 

Can I do that If in the with statement?


No,,, it would be something like

with Paging(RowNo, ID, Name, Description, LengthSeconds, Rating, Url, ThumbnailFileName, AddedAt) AS
(
     select ... 

     WHERE @SortType is not null
     UNION ALL
     select ... 

     WHERE @SortType is null
)...

If the query is that simple though, then you wouldn't need a CTE: it doesn't add any readibility


You could use a union where the top side corresponds to the first half of the if:

select  ...
where   @SortType is null
union all
select  ...
where   @SortType not null null

An if statement is not allowed inside a query, only to control flow around queries. So an if inside a with is not allowed.

0

精彩评论

暂无评论...
验证码 换一张
取 消