在Fullname列上进行SQL排序

时间:2013-12-02 19:38:50

标签: sql sql-server sql-server-2008

我有一个包含全名列的表,名为userFullName

我正在尝试创建一个正确的选择语句来显示一个' -Select User - '下拉列表的值,但按userFullName字段中的姓氏对结果集进行排序。

我怎么能:

  1. 获得正确工作的排序?
  2. 仍然保留-Select User-作为第一选择?
  3. SQL语句:

    SELECT
        0 As UserID, '-Select User-' As UsersName, '' As Surname 
    
    UNION ALL
    
    SELECT
        userID As UserID, userFullName As UsersName, 
        REVERSE(SUBSTRING(REVERSE([userFullName]), 0, CHARINDEX(' ', REVERSE([userFullName])))) As Surname 
    FROM 
        vwSelectUser 
    ORDER BY 
        REVERSE(SUBSTRING(REVERSE([userFullName]), 0, CHARINDEX(' ', REVERSE([userFullName]))))
    

    我收到以下错误

      

    Msg 207,Level 16,State 1,Line 6
      列名称无效' userFullName'。
      Msg 207,Level 16,State 1,Line 6
      列名称无效' userFullName'。
      Msg 104,Level 16,State 1,Line 6
      如果语句包含UNION,INTERSECT或EXCEPT运算符,则ORDER BY项必须出现在选择列表中。

    是的,userFullNamevwSelectUser

    中的有效列

1 个答案:

答案 0 :(得分:5)

最好的方式是分别存储名字和姓氏,但是你得到的就是这样:

SELECT * FROM 
(
    Select 0 As UserID, '-Select User-' As UsersName, CONVERT(VARCHAR(100),'') As Surname 
    Union All 
    Select userID As UserID, userFullName As UsersName, 
    REVERSE(SUBSTRING(REVERSE([userFullName]), 0, CHARINDEX(' ', REVERSE([userFullName])))) As Surname 
    From vwSelectUser 
) AS A
Order By Surname