有时候数据库表中某些字段是由中文和字母或数字组成,而有时候我们又需要将该字段中的中文去掉。想要实现这种需求的方法有很多,下面就是其中一种解决方法。
首先我们先建立测试数据
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
结果:
创建函数:
--去除输入字符串中的中文
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=dbo.fun_del_chinese(name)
from
test
执行结果:
可以看到全部由中文组成的字段被清空了,但是有时候我们需要全部由中文组成的字段保留下来,这时候可以稍微加一些判断。
执行:
update
test
set
name=dbo.fun_del_chinese(name)
from
test
where
len(name)*2!=datalength(name)--排除全部由中文组成字段
执行结果: