目的: 过滤某个字段中含有空格的数据。比如:字段name中有数据“nick zhang”, “nickZhang”,我想选出“nick zhang”。

常见做法:

使用charindex()函数:
select name from testUser where charindex(‘ ‘, name) > 0;

原理:使用charindex()判断当前的name是否包含空格。

Code:
Create table testUser (name nvarchar(2000));
insert into testUser values('nick zhang');
insert into testUser values('nickZhang');
-- filter data with space
select name from testUser where charindex(' ', name) > 0;

Result:
name
1. nick zhang

如果需求变为要将所有空格都去掉,那么可以使用

replace()函数: 用第三个表达式替换第一个字符串表达式中出现的所有第二个给定字符串表达式。

REPLACE ( 'string_expression1' , 'string_expression2' , 'string_expression3' )

select name= REPLACE(name, ' ', '') from testUser;

Result:
name
1. nickzhang
2. nickZhang

转载自:http://zhangyue.info/2011/07/sql%e8%bf%87%e6%bb%a4%e6%9c%89%e7%a9%ba%e6%a0%bc%e7%9a%84%e6%95%b0%e6%8d%ae/

相关文章:

  • 2022-12-23
  • 2022-03-05
  • 2021-07-16
  • 2022-12-23
  • 2022-02-18
  • 2022-02-25
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-14
  • 2021-11-07
  • 2022-12-23
  • 2021-10-11
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案