Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TSQL:If语句在With语句中_Sql_Sql Server_Tsql - Fatal编程技术网

TSQL:If语句在With语句中

TSQL:If语句在With语句中,sql,sql-server,tsql,Sql,Sql Server,Tsql,我的问题是我想将两个SP合并到一个SP中。生成的sp的骨架是: with Paging(RowNo, ID, Name, Description, LengthSeconds, Rating, Url, ThumbnailFileName, AddedAt) AS ( (if(@SortType is null) begin ... select ... end else begin ...

我的问题是我想将两个SP合并到一个SP中。生成的sp的骨架是:

 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 ... 

如果在with语句中,我可以这样做吗?

不,,,它将类似于

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
)...

如果查询是如此简单,那么您就不需要CTE:它不增加任何可读性

您可以使用一个
联合体
,其中顶部对应于
If
的前半部分:

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

查询中不允许使用
if
语句,该语句仅用于控制查询周围的流。因此,不允许在带有的
中使用
if

如何在没有CTE的情况下进行分页?可以通过添加OVER子句“ROW_NUMBER()OVER(ORDER by…”来进行分页在SQL Server 2011中,使用
FETCH
OFFSET
进行分页将更加容易。但是,仍然不支持在
OVER
子句中引用下一行/上一行。