4

嗨,下面的查询是一个更大的复杂查询的原型问题是我应该能够根据用户输入以任何顺序(即 ASC 和 DESC)对任何列进行排序。

CREATE table #Table1(
Name varchar(10) PRIMARY key,
DOB DateTime,
Rate numeric(10,2)  
)

INSERT INTO #Table1 (Name,DOB,Rate) values ('Name1','2/2/2012',10.23)
INSERT INTO #Table1 (Name,DOB,Rate) values ('Name2','3/2/2012',120.23)
INSERT INTO #Table1 (Name,DOB,Rate) values ('Name3','4/2/2012',110.23)
INSERT INTO #Table1 (Name,DOB,Rate) values ('Name4','5/2/2012',140.23)
INSERT INTO #Table1 (Name,DOB,Rate) values ('Name15','6/2/2012',130.23)
INSERT INTO #Table1 (Name,DOB,Rate) values ('Name6','2/21/2012',1120.23)

Declare @SortColumn varchar(10)
DECLARE @SortExpression varchar (10)

SET @SortColumn = 'DOB'
SET @SortExpression = 'DESC' -- Need to sort in both ASC and DESC

Select 
            Name,
            DOB,
            Rate,
            ROW_NUMBER() OVER 
                (ORDER BY 
                    CASE WHEN @SortColumn = 'Name' then Name
                         WHEN @SortColumn = 'DOB' THEN DOB
                         WHEN @SortColumn = 'Rate' THEN Rate
                    END  +  @SortExpression 
                ) AS RowNumber  
                FROM 
                #Table1
4

2 回答 2

2

看起来你需要CAST()CONVERT()中的项目CASE才能让它工作:

Declare @SortColumn varchar(10)
DECLARE @SortExpression varchar (10)

SET @SortColumn = 'DOB'
SET @SortExpression = 'DESC' -- Need to sort in both ASC and DESC

Select 
   Name,
   DOB,
   Rate,
   ROW_NUMBER() OVER 
   (ORDER BY 
       CASE WHEN @SortColumn = 'Name' then Name
            WHEN @SortColumn = 'DOB' THEN convert(char(10), DOB, 120)
            WHEN @SortColumn = 'Rate' THEN Cast(Rate as varchar(10))
       END  ASC
    ) AS RowNumberASC,
    ROW_NUMBER() OVER 
    (ORDER BY 
       CASE WHEN @SortColumn = 'Name' then Name
            WHEN @SortColumn = 'DOB' THEN convert(char(10), DOB, 120)
            WHEN @SortColumn = 'Rate' THEN Cast(Rate as varchar(10))
      END DESC
    ) AS RowNumberDESC
FROM Table1

请参阅带有演示的 SQL Fiddle

正如@Martin 指出的那样,ASC,DESC不能被参数化。

于 2012-08-22T16:43:35.723 回答
0

如果需要在ASCDESC动态之间切换,则必须使用动态语句。
SQL Fiddle在这里。注意SQL 注入

EXECUTE(' SELECT Name, DOB, Rate,'
      + ' ROW_NUMBER() OVER( ORDER BY ' + @SortColumn + ' ' + @SortExpression
      + ' ) AS RowNumber'
      + ' FROM Table1');

如果您的查询很复杂,请考虑将其放入视图中并从该视图中进行选择以允许在编译时检查该部分。

于 2012-08-22T16:57:29.147 回答