SQL Server 字段值包含中英文按照拼音混合排序

  • 创建函数
USE SH_CFG
GO

--全部扔进去执行,不用修改
Create FUNCTION dbo.fnpbGetPYFirstLetter
(
@str NVARCHAR(4000)
)
/*
select dbo. fnpbGetPYFirstLetter ('中國香港')
*/
RETURNS NVARCHAR(4000)
--WITH ENCRYPTION
AS
BEGIN
DECLARE @WORD NCHAR(1),@PY NVARCHAR(4000)

SET @PY=''

WHILE LEN(@STR)>0
BEGIN
SET @WORD=LEFT(@STR,1)

--如果非漢字字符﹐返回原字符
SET @PY=@PY+(CASE WHEN UNICODE(@WORD) BETWEEN 19968 AND 19968+20901
THEN (
SELECT TOP 1 PY
FROM
(
SELECT 'A' AS PY,N'' AS WORD
UNION ALL SELECT 'B',N'簿'
UNION ALL SELECT 'C',N''
UNION ALL SELECT 'D',N''
UNION ALL SELECT 'E',N''
UNION ALL SELECT 'F',N''
UNION ALL SELECT 'G',N''
UNION ALL SELECT 'H',N''
UNION ALL SELECT 'J',N''
UNION ALL SELECT 'K',N''
UNION ALL SELECT 'L',N''
UNION ALL SELECT 'M',N''
UNION ALL SELECT 'N',N''
UNION ALL SELECT 'O',N''
UNION ALL SELECT 'P',N''
UNION ALL SELECT 'Q',N''
UNION ALL SELECT 'R',N''
UNION ALL SELECT 'S',N''
UNION ALL SELECT 'T',N''
UNION ALL SELECT 'W',N''
UNION ALL SELECT 'X',N''
UNION ALL SELECT 'Y',N''
UNION ALL SELECT 'Z',N''
) T
WHERE WORD>=@WORD COLLATE CHINESE_PRC_CS_AS_KS_WS
ORDER BY PY ASC
)
ELSE @WORD
END)
SET @STR=RIGHT(@STR,LEN(@STR)-1)
END

RETURN @PY

END

Go
  • 查询
SELECT Name FROM TESTTB ORDER BY dbo.fnpbGetPYFirstLetter(Name)

 

posted @ 2021-12-16 19:02  来瓶冰镇可乐吧  阅读(87)  评论(0编辑  收藏  举报