我有一个存储过程,可以接受2个不同的参数。第一个参数将确定我要排序的列,第二个参数将确定它是ASC
还是DESC
Create Procedure Some_SP
@sortcolumn varchar(10)
@sortorder varchar(10)
AS
Select * from empTable
Order by
CASE @sortcolumn WHEN 'First_Name' THEN fname END,
CASE @sortcolumn WHEN 'Last_Name' THEN lname END,
CASE @sortcolumn WHEN 'ID' THEN empID END,
CASE @sortorder WHEN 'ascending' THEN ASC END,
CASE @sortorder WHEN 'descending' THEN DESC END
它给了我语法错误。如何修复它以便我的CASE语句中有两个条件?
答案 0 :(得分:5)
以下内容可行:
Select * from empTable
Order by
CASE WHEN @sortcolumn = 'First_Name' AND @SortOrder = 'ascending' THEN fname END ASC,
CASE WHEN @sortcolumn = 'First_Name' AND @SortOrder = 'descending' THEN fname END DESC
等...
为了避免手动输入每个case语句,你可以写一个" generator"用于创建此脚本的脚本(如果表定义发生更改,则特别好):
SELECT
'CASE WHEN @SortColumn = ''' + C.name + ''' AND @SortOrder = ''ascending'' THEN ' + C.name + ' END ASC,' + CHAR(13) + CHAR(10) +
'CASE WHEN @SortColumn = ''' + C.name + ''' AND @SortOrder = ''descending'' THEN ' + C.name + ' END DESC,'
FROM sys.columns C
WHERE C.object_id = object_id('[Schema].[Table]')
答案 1 :(得分:2)
如果您想避免动态SQL并使用2x条件,可以使用row_number
例如:
declare @t table (string varchar(50), number int)
insert @t values ('a',9),('f',2),('c',1)
declare
@sc varchar(10) = 'number', -- or 'string', etc
@so varchar(10) = 'desc' -- or 'asc'
select *
from
(
select
*,
case @sc when 'string' then ROW_NUMBER() over (order by string)
when 'number' then ROW_NUMBER() over (order by number)
end rn
from @t
) v
order by
case @so when 'desc' then -rn else rn end
答案 2 :(得分:1)
您只需复制并粘贴并运行即可。我讨厌动态SQL,不要这样做。
不幸的是,您必须复制查询....但它可以解决您的具体问题。
DECLARE
@sortcolumn varchar(10),
@sortorder varchar(10)
SET @sortcolumn = 'fname'
SET @sortorder = 'DESC'
DECLARE
@Data TABLE
(
fname nvarchar(10),
lname nvarchar(10),
empID int
)
INSERT INTO @Data VALUES ('BBB', 'BBB', 2)
INSERT INTO @Data VALUES ('AAA', 'AAA', 1)
IF @sortorder = 'DESC' BEGIN
SELECT
*
FROM
@Data
ORDER BY
CASE
WHEN @sortcolumn = 'fname' THEN fname
WHEN @sortcolumn = 'lname' THEN lname
END
DESC
END ELSE BEGIN
SELECT
*
FROM
@Data
ORDER BY
CASE
WHEN @sortcolumn = 'fname' THEN fname
WHEN @sortcolumn = 'lname' THEN lname
END
END
答案 3 :(得分:1)
修改Jon的答案,将ORDER BY列表限制为2而不是2 * #columns
SELECT *
FROM MyTable
CROSS APPLY (VALUES
('First_Name',fname),
('Last_Name' ,lname),
('Id' ,ID )
) sort(SortColumn, SortValue)
WHERE SortColumn = @SortColumn
ORDER BY
CASE @SortOrder WHEN 'ascending' THEN SortValue END ASC,
CASE @SortOrder WHEN 'descending' THEN SortValue END DESC