码迷,mamicode.com
首页 > 数据库 > 详细

sql 获取字符串首字母,循环

时间:2017-09-27 13:14:32      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:locate   where   table   com   rom   spel   nvarchar   turn   spell   

//字符串首字母
CREATE FUNCTION GetInitialLetter(@ChineseString NVARCHAR(4000)) 
RETURNS NVARCHAR(4000) 
AS
BEGIN
 
DECLARE @SingleCharacter NCHAR(1),
@ReturnString NVARCHAR(4000) 
SET @ReturnString = ‘‘ 

WHILE LEN(@ChineseString)>0 
BEGIN

--依次取单个字符
SET @SingleCharacter = LEFT(@ChineseString,1) 

----汉字字符,返回字符对应首字母,非汉字字符,返回原字符
IF(UNICODE(@SingleCharacter) BETWEEN 19968 AND 19968+20901)
SET @ReturnString = @ReturnString + 
(SELECT TOP 1 PY FROM
(SELECT A AS PY,N AS ChineseCharacters 
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 
)SpellingTable 
where ChineseCharacters > = @SingleCharacter COLLATE Chinese_PRC_CS_AS_KS_WS 
ORDER by PY ASC)
ELSE
SET @ReturnString = @ReturnString + @SingleCharacter

 
SET @ChineseString = RIGHT(@ChineseString,LEN(@ChineseString)-1) 

END
 
RETURN @ReturnString 

END
GO

//调用方式
SELECT dbo.GetInitialLetter(中锴华章)
//循环
declare @id varchar(50)
declare @name varchar(50)
declare my_cursor cursor
for(select id,name from community)
open my_cursor;
fetch next from my_cursor into @id,@name;
while @@FETCH_STATUS=0
    begin 
        print @name;
        update community set english_name=(dbo.GetInitialLetter(@name)) where id=@id;
        fetch next from my_cursor into @id,@name;
    end
close my_cursor;
deallocate my_cursor;
go

 

sql 获取字符串首字母,循环

标签:locate   where   table   com   rom   spel   nvarchar   turn   spell   

原文地址:http://www.cnblogs.com/vaevvaev/p/7600825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!