案例按顺序排列

时间:2012-09-04 11:00:38

标签: sql sql-server-2008-r2

我有这个表用户 我需要按参数排序选择结果,但是当我对varchar字段进行排序时遇到问题 比如userName字段。 怎么解决这个问题?

----------------------------------------
| userID | UserName | password |...... |
----------------------------------------
| int    | varchar  | varcahr  | ..... |

    declare @index varchar(100)
    set @index = 2
    select * From users
    order by case @index 
                            when 1 then Number
                            when 2 then CAST(LoginName AS INT)
                            Else Password
                End

3 个答案:

答案 0 :(得分:3)

将数字转换为char,而不将char转换为数字

case @index
      WHEN 1 THEN RIGHT('0000000000'+ CAST(UserId AS VARCHAR(10)), 10)
      WHEN 2 THEN UserName -- or LoginName, maybe a typo ?
      ELSE Password
      end

答案 1 :(得分:0)

您无法将大多数varchars转换为int,因此您必须按varchars排序

order by格式化为

      case @index
      when 1 then RIGHT('000000'+ CONVERT(Varchar(6), UserID)
      when 2 then LoginName
      end

答案 2 :(得分:0)

declare @pSORT_PARAM VARCHAR(400) -- HERE YOU HAVE TO PASS COLUMN NAME AS PARAMETER

DECLARE @pSORT_ORDER VARCHAR(10) -- HERE YOU HAVE TO PASS SORT ORDER AS ASC OR DESC

DECLARE @pQUERY VARCHAR(400)

SET @pSORT_ORDER=' ASC '

SET @pQUERY='SELECT * FROM USERS'

set @pQUERY =@pQUERY + ISNULL(' ORDER BY '+ @pSORT_PARAM + @pSORT_ORDER,'')

EXEC SP_EXECUTESQL @pQUERY