sqlServer去除字段中的中文

时间:2022-07-02 04:42:10

很多时候数据库表中某些字段是由中文和字母或数字组成,但有时我们又需要将字段中的中文去掉。想要实现这种需求的方法有很多,下面就是其中一种解决方法。

首先我们先建立测试数据

create table test(
id int primary key identity(1,1),
name varchar(20) not null
)

insert into test(name) values('测试2')
insert into test(name) values('测试a')
insert into test(name) values('测试')
insert into test(name) values('abc')
insert into test(name) values('123')
insert into test(name) values('abc123')

select * from test

 

结果:

sqlServer去除字段中的中文

创建函数:

--去除输入字符串中的中文
create function fun_del_chinese
(@col varchar(1000))
returns varchar(1000)
AS
begin
    declare @returnchar varchar(1000),@len int
    select @returnchar='',@len=1
 
    while(@len<=len(@col))
    begin
        if(ASCII(substring(@col,@len,1))<122)
        set @returnchar=@returnchar+substring(@col,@len,1)
        set @len=@len+1
    end
return @returnchar
end
go

 执行:

update test set name=t2.name
from test t1,
(select id,dbo.fun_del_chinese(name) name from test
where len(name)*2!=datalength(name)--排除全部由中文组成字段
) t2
where t1.id=t2.id

 

执行结果:

sqlServer去除字段中的中文