我有以下 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/