exec sp_executesql N'WITH SearchResult AS 
(   SELECT Row_Number() OVER (ORDER BY  @SortExpression +'' '' + @SortDirection) AS RowID, 
        UserID,
        FirstName,
        LastName,
        UserName,
        Status,
        UserRole
    FROM dbo.Users
    WHERE (Status = @Status OR @Status = -1) 
      AND (FirstName LIKE ''%''+@Keyword+''%'' OR LastName LIKE ''%''+@Keyword+''%'' OR UserName LIKE ''%''+@Keyword+''%'' OR  @Keyword = '''')
) SELECT * FROM SearchResult WHERE RowID > @PageIndex * @PageSize AND RowID <= (@PageIndex + 1) * @PageSize',
N'@Keyword nvarchar(4000),@Status int,@PageIndex int,@PageSize int,@SortExpression nvarchar(8),@SortDirection nvarchar(4)',
@Keyword=N'',@Status=-1,@PageIndex=0,@PageSize=1,@SortExpression=N'USERNAME',@SortDirection=N'asc'
在上面的SQL语句中指定的排序参数 @SortExpression @SortDirection为什么不起作用,无论@SortDirection=N'asc'还是@SortDirection=N'desc',执行的结果始终是一样的顺序?

解决方案 »

  1.   

    create table tb (id int,name varchar(10))
    insert into tb select 1,'c'
    insert into tb select 2,'b'
    insert into tb select 3,'a'declare 
    @ordername varchar(10),
    @ordertype varchar(10),
    @sql nvarchar(4000)
    set @ordername='id'
    set @ordertype='desc'
    set @sql='select *,row_number() over(order by '+@ordername+' '+ @ordertype+')as a from tb'
    exec (@sql)id name a
    3 a 1
    2 b 2
    1 c 3
      

  2.   

    row_number--是生成序号。。
    exec   sp_executesql   N'WITH   SearchResult   AS   
    (       SELECT   Row_Number()   OVER   (ORDER   BY     @SortExpression   +''   ''   +   @SortDirection)   AS   RowID,   
                    UserID, 
                    FirstName, 
                    LastName, 
                    UserName, 
                    Status, 
                    UserRole 
            FROM   dbo.Users 
            WHERE   (Status   =   @Status   OR   @Status   =   -1)   
                AND   (FirstName   LIKE   ''%''+@Keyword+''%''   
                OR   LastName   LIKE   ''%''+@Keyword+''%''   
                OR   UserName   LIKE   ''%''+@Keyword+''%''   
                OR     @Keyword   =   '''') )   
    SELECT   *   FROM   SearchResult   
    WHERE   RowID   >   @PageIndex   *   @PageSize   AND 
     RowID   <=   (@PageIndex   +   1)   *   @PageSize' order by RowID asc, --**这里加上
    N
    '@Keyword   nvarchar(4000),@Status   int,@PageIndex   int,@PageSize   int,@SortExpression   nvarchar(8),@SortDirection   nvarchar(4)', 
    @Keyword=N'',@Status=-1,@PageIndex=0,@PageSize=1,@SortExpression=N'USERNAME',@SortDirection=N'asc'