SQL RTRIM()用法及代码示例

您所在的位置:网站首页 ltrim函数用法hive SQL RTRIM()用法及代码示例

SQL RTRIM()用法及代码示例

2024-07-04 10:27| 来源: 网络整理| 查看: 265

SQL RTRIM 函数是一个字符串函数,用于删除字符或字符串右侧的空格。 RTRIM 或 Right Trim 函数用于 SQL 中的数据清理和操作。

在此示例中,我们将学习 RTRIM 函数的基础知识,并通过不同用例的示例了解它的工作原理。

RTRIM() SQL 中的函数

SQL RTRIM() 函数允许我们从字符串中删除尾随空格。尾随空格是字符串右端存在的冗余空格。例如,在 “GFG”,字符串右端有 5 个空白空格。

如果字符串开头有多余的空格。例如:“GFG”,字符串开头有5个空格”,这些称为前导空白。

RTRIM 函数适用于MySQL 4.0、SQL Server(从 2008 年开始)、Azure SQL 数据库、Azure SQL 数据仓库、并行数据仓库、Oracle 和所有其他主要数据库系统。

用法

RTRIM( input_text);

OR

RTRIM(column_name) AS trimmed_nameFROM table_name;

SQL RTRIM 函数示例

让我们看看 SQL 中 RTRIM 函数的一些示例,并了解它在不同用例的示例中的工作原理。

示例 1:使用 RTRIM 函数删除字符串中的尾随空格

RTRIMSQL 中的函数用于删除字符串中的尾随空格。下面举几个例子来说明其用法:

SELECT (' Geeks for Geeks ') as "Before RTRIM()", RTRIM(' Geeks for Geeks ') as "After RTRIM()"; 输出

正如我们所看到的,字符串右端的空格被删除,而左侧的空格保持原样。

rtrim function example

RTRIM()函数

示例 2:在表列上使用 RTRIM 函数

假设我们有一个名为 Students 的表,其中包含 id 和 name。 RTRIM() 函数将修剪给定列中的尾随空格。

首先,我们使用以下命令创建一个表 GFG。

CREATE TABLE GFG( id integer, name varchar(40)); INSERT INTO GFG VALUES (1,"kiran "), (2," navya ");

输出:

gfg table created

GFG 表的输出。

现在我们将对列名称使用 RTRIM 函数。

SELECT name as "Before RTRIM()", RTRIM(name) as "AFTER RTRIM()" from gfg;输出:

上面的查询结果有两列,第一列表示使用 RTRIM() 函数之前的 name 列,第二列表示应用 RTRIM() 函数之后 name 列的值RTRIM()函数。正如我们所看到的,尾随空格被删除,第二列的宽度“TRIM()之后” 被缩短。

Screenshot-2023-12-26-155409

应用RTRIM()函数后的输出。

示例 3:将 RTRIM 函数与变量一起使用DELIMITER //

CREATE PROCEDURE RTRIM_Example()BEGIN -- Declare a variable DECLARE input_string VARCHAR(15); -- Assign a value to the variable SET input_string = 'Hello '; -- Use the variable in a query SELECT CONCAT(RTRIM(input_string), ' World') AS result;END //DELIMITER ;

-- Call the stored procedureCALL RTRIM_Example();

输出:

我们在中声明一个变量存储过程并为其赋值。我们改变了分隔符到 “//” 将过程视为一个语句。然后我们使用CONCAT()函数连接声明的变量和“World”。我们还在 CONCAT 函数中的声明变量上使用了 RTRIM 函数,正如我们在结果中看到的,RTRIM 方法从声明的变量中删除了空格。

关于 SQL RTRIM 函数的要点RTRIM() function removes the trailing spaces in the given string or removes trailing spaces for all the values present in a specific column in the table. It allows only one parameter i.e. either a string or a column having values of string type. It is supported in all major database systems. When used in SELECT statements, the function improves the readability of results by eliminating unnecessary white spaces.


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3