据我所知,我可以按照以下的sql查询部分的顺序使用变量:
order by
case when @var1 = 'priority' then priority end desc,
case when @var2 = 'report_date' then report_date end asc
但是我如何在asc和desc部分使用变量呢?
答案 0 :(得分:40)
没有Dynamic SQL
每个选项它的子句例如:
ORDER BY
case when @var1 = 'priority asc' THEN priority END ASC ,
case when @var1 = 'priority desc' then priority end DESC,
case when @var2 = 'report_date asc' then report_date end ASC,
case when @var2 = 'report_date desc' then report_date end DESC
答案 1 :(得分:7)
假设您的变量@var3
存储了'ASC'
或'DESC'
个关键字,您可以这样写:
order by
case when @var1 = 'priority' and @var3 = 'DESC' then priority end DESC,
case when @var1 = 'priority' and @var3 = 'ASC' then priority end ASC,
case when @var2 = 'report_date' and @var3 = 'ASC' then report_date end ASC,
case when @var2 = 'report_date' and @var3 = 'DESC' then report_date end DESC
答案 2 :(得分:7)
您可以通过向Order by
引入multiplier hack来动态地对多种类型进行排序。实现将取决于您能够将每个可排序字段转换为整数字段,如下所示:
DECLARE @Var1 NVARCHAR(20);
DECLARE @Var2 NVARCHAR(3);
DECLARE @OrderHack INT;
SET @Var1 = 'priority';
SET @Var2 = 'DESC';
IF (@Var2 = 'ASC')
SET @OrderHack = 1;
ELSE
SET @OrderHack = -1;
SELECT *
FROM SortTable
ORDER BY
CASE @var1
WHEN 'priority'
THEN CONVERT(INT, [priority]) * @OrderHack
WHEN 'report_date'
THEN CONVERT(INT, report_date) * @OrderHack
END;
修改强>
只是澄清一下,根据@t-clausen.dk
的观点,黑客依赖于转换回代表订单的递增数字类型。例如如果您需要DATETIME
更高的分辨率以确保排序中也考虑时间组件,则INT @OrderHack
可以替换为FLOAT
或DECIMAL
等。 :使用此技术对*CHAR
列进行排序可能具有挑战性,尤其是在考虑了大小写和重音敏感度的情况下。
答案 3 :(得分:5)
试试这个 -
DECLARE
@column VARCHAR(15) = 'object_id'
, @order CHAR(4) = 'DESC'
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
SELECT *
FROM sys.objects
ORDER BY ' + @column + ' ' + @order
PRINT @SQL
EXEC sys.sp_executesql @SQL