select ... variable = case when ... end from ... order by len(@variable)

时间:2012-07-31 07:06:06

标签: sql sql-server-2008 sql-server-2008r2-express

我要做的是连接表的两个字段,按连接字段的下降长度对它们进行排序,得到最高结果......

这是我用来尝试实现这个的SQL ......

declare @color nvarchar(255);
declare @board_name nvarchar(255);

select top(1)
    @board_name = board_name, 
    @color = base_color + case when shade_color is null then '' else '/' + shade_color end 
from 
    cut_vinyl
order by 
    len(@color) desc;

select @board_name, @color;

所以,如果我有cut_vinyl

的下表
board_name | base_color | shade_color
=====================================
board0001  | clear      | NULL
board0002  | clear      | blue
board0003  | bronze     | bronze
board0004  | bronze     | green
board0005  | bronze     | blue
board0006  | bronze     | NULL

然后我希望 @board_name board0003 @color 铜牌/铜牌,但我似乎得到的结果是 @board_name = board0001 @color = 清除

1 个答案:

答案 0 :(得分:1)

您订购variable

order by 
    len(@color) desc;

如果您正在寻找最长的颜色,请使用:

order by 
    len(base_color) + len(shade_color) desc;

代替。