sql-server - 排序依据和大小写

标签 sql-server sql-order-by case

我有以下 SQL 脚本:

ALTER PROC [dbo].[getRequests]
@SortBy             VARCHAR(50) = 'Date'
AS
SELECT  [ReqDate], [RequestorOrg], [RequestCategory],
        [ReqDescription], [OrgCountVote]
ORDER BY 
        CASE WHEN @SortBy = 'Date (oldest first)'   THEN [ReqDate]          END ASC, [OrgCountVote] DESC,
        CASE WHEN @SortBy = 'Date (newest first)'   THEN [ReqDate]          END DESC, [OrgCountVote] ,
        CASE WHEN @SortBy = 'Number of Votes'       THEN [OrgCountVote]     END DESC, reqdate,
        CASE WHEN @SortBy = 'Organisation'          THEN [RequestorOrg]     END,
        CASE WHEN @SortBy = 'Category'              THEN [RequestCategory]  END;

ORDER BY 中的前两种情况有多个要排序的列。

当我尝试保存脚本时,它会显示以下消息:

Msg 169, Level 15, State 1, Procedure getRequests, Line 8
A column has been specified more than once in the order by list. Columns in the order by list must be unique.

如何确保列是唯一的

最佳答案

我建议您使用这种类型的存储过程:

ALTER PROC [dbo].[getRequests]
@SortBy             VARCHAR(50) = 'Date'
AS
BEGIN
DECLARE @sql varchar(max) 

SET @sql = 'SELECT  [ReqDate], [RequestorOrg], [RequestCategory], [ReqDescription], [OrgCountVote] ' +
           'ORDER BY ' +
                CASE @SortBy
                    WHEN 'Date (oldest first)' THEN '[ReqDate] ASC, [OrgCountVote] DESC'
                    WHEN 'Date (newest first)' THEN '[ReqDate] DESC, [OrgCountVote] '
                    WHEN 'Number of Votes'     THEN '[OrgCountVote] DESC, reqdate'
                    WHEN 'Organisation'        THEN '[RequestorOrg]'
                    WHEN 'Category'            THEN '[RequestCategory]'
                END
EXEC(@sql)
END

关于sql-server - 排序依据和大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339926/

相关文章:

sql-server - 关系数据仓库中的引用完整性。这值得么?有哪些替代方案?

sql - 如何将更新的记录移动到历史表中?

sql-server - Insert Into Table () Values(),() 由于错误部分插入

sql - 对于多个 sql order by 子句,即使之前的 order by 已经证明行不相等,所有的 order bys 是否都运行?

mysql - 有没有办法通过 WHERE IN 语句将嵌套子查询中的别名列名传递给 UPDATE 语句?

UPDATE + CASE WHEN + EXISTS + SELECT MAX 的 MySQL 语法

mysql条件字段更新

sql - 删除重复的子查询

MYSQL:如何在包含 'Best match'的查询中实现按 `UNION ALL`排序

MYSQL 按大小写排序