我有一个包含全名列的表,名为userFullName
我正在尝试创建一个正确的选择语句来显示一个' -Select User - '下拉列表的值,但按userFullName
字段中的姓氏对结果集进行排序。
我怎么能:
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项必须出现在选择列表中。
是的,userFullName
是vwSelectUser
答案 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