SQL SERVER字符串中的空格去除

本文介绍SQL中的LTRIM和RTRIM函数,它们用于分别删除字符串起始和末尾的空格。通过具体示例展示了如何使用这两个函数来清理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.LTRIM 
删除起始空格后返回字符表达式。

语法 
LTRIM   (   character_expression   )

参数 character_expression 是字符或二进制数据表达式。character_expression   可以是常量、变量或列。character_expression   必须是可以隐性转换为   varchar   的数据类型。否则,使用   CAST   显式转换   character_expression。

返回类型 
varchar

注释 
兼容级别可能影响返回值。有关兼容级别的更多信息,请参见   sp_dbcmptlevel。  

示例 
下例使用   LTRIM   字符删除字符变量中的起始空格。

DECLARE   @string_to_trim   varchar(60) 
SET   @string_to_trim   =   '           Five   spaces   are   at   the   beginning   of   this 
      string. ' 
SELECT   'Here   is   the   string   without   the   leading   spaces:   '   +   
      LTRIM(@string_to_trim) 
GO

下面是结果集:

------------------------------------------------------------------------ 
Here   is   the   string   without   the   leading   spaces:   Five   spaces   are   at   the   beginning   of   this   string.                          

(1   row(s)   affected)

2.RTRIM 
截断所有尾随空格后返回一个字符串。

语法 
RTRIM   (   character_expression   )   

参数 
character_expression 由字符数据组成的表达式。character_expression   可以是常量、变量,也可以是字符或二进制数据的列。character_expression   必须为可隐性转换为   varchar   的数据类型。否则请使用   CAST   函数显式转换   character_expression。 
 

返回类型 
varchar  

注释  兼容级别可能影响返回值。有关更多信息,请参见   sp_dbcmptlevel。  


示例 
下例显示如何使用   RTRIM   删除字符变量中的尾随空格。

DECLARE   @string_to_trim   varchar(60) 
SET   @string_to_trim   =   'Four   spaces   are   after   the   period   in   this   sentence.         ' 
SELECT   'Here   is   the   string   without   the   leading   spaces:   '   +   CHAR(13)   + 
      RTRIM(@string_to_trim) 
GO

下面是结果集:

(1   row(s)   affected) 
------------------------------------------------------------------------   
Here   is   the   string   without   the   leading   spaces:   Four   spaces   are   after   the   period   in   this   sentence.                       
(1   row(s)   affected)

你可以RTRIM(LTRIM(字段)) --删除起始空格,截断所有尾随空格后返回字符串

select   ltrim(rtrim(title))   from   table1

转载于:https://www.cnblogs.com/jingzhi2017/p/7852132.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值