1

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

----------------------------------------
| 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
4

3 回答 3

3

将数字转换为字符,而不是将字符转换为数字

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
于 2012-09-04T11:04:14.310 回答
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
于 2012-09-04T12:48:50.867 回答
0

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

格式化你order by

      case @index
      when 1 then RIGHT('000000'+ CONVERT(Varchar(6), UserID)
      when 2 then LoginName
      end
于 2012-09-04T11:04:05.480 回答