【问题标题】:Removing the first 5 characters of each entry of a column STORED PROCEDURE删除列存储过程的每个条目的前 5 个字符
【发布时间】:2023-04-03 11:46:02
【问题描述】:

我有 reservation 表,在该表中有一个名为 campground 的列。 campground 列的每个条目都与其他条目非常相似,例如:

ALBE/阿尔伯塔海滩家庭房车公园

谁能告诉我如何使用从该列中的每个条目中删除 5 个字符的存储过程来删除该列中每个条目的前 5 个字符?

到目前为止我尝试过的代码如下:

UPDATE reservation
SET RIGHT(campground, LEN(campground) - 5)

有人可以帮我创建一个具有上述功能的存储过程吗?

谢谢!!

【问题讨论】:

  • 为什么是存储过程?
  • mysql 还是 postgres?请仅标记您正在使用的一个数据库。

标签: mysql sql string postgresql pgadmin-4


【解决方案1】:

您真的要删除字符串的 前 5 个字符,还是要删除直到第一个正斜杠的所有内容?

此处的其他答案解决了您的字面问题。 回答了你可能真的问的问题(PostgreSQL 方言):

select substr(campground,position('/' in campground)+1)
from (values
     ('ABC/American Bike Camp')
    ,('ALBE/Alberta Beach Family RV Park')) t(campground)
;
            substr
------------------------------
 American Bike Camp
 Alberta Beach Family RV Park
(2 rows)

在更新语句中使用该表达式:

update reservation
set campground = substr(campground,position('/' in campground)+1)
where campground like '%/%'
;

(包含 where 子句以确保它不会更新已更新的行)

【讨论】:

    【解决方案2】:

    您可以使用substring 函数与起始位置

    select substring(campground from 6);
    

    【讨论】:

      【解决方案3】:

      在 MySQL 中你可以使用非常简单的查询:

      UPDATE reservation
      SET campground = MID(campground, 6);
      

      在 PostgreSQL 中使用 substring 而不是 mid:

      UPDATE reservation
      SET campground = substring(campground, 6);
      

      小心,这个查询会改变你的源数据,没有回滚选项。

      【讨论】:

        【解决方案4】:

        您错过了在 set 子句中给出列名:

        UPDATE reservation
        SET campground = RIGHT(campground, LEN(campground) - 5)
        

        【讨论】:

          【解决方案5】:

          我只会使用substr(),这样可以让表达式更简单:

          substr(campground, 6)
          

          MySQL 和 Postgres 都支持这种语法。

          如果你想要更新查询,那么:

          update reservation set campground = substr(campground, 6)
          

          【讨论】:

            【解决方案6】:

            您可以在 PostgreSQL 中使用split_part()

            UPDATE reservation
               SET campground = split_part(campground, '/', 2)
            

            【讨论】:

              猜你喜欢
              • 2020-06-28
              • 1970-01-01
              • 2022-01-04
              • 2017-07-18
              • 1970-01-01
              • 1970-01-01
              • 2016-06-04
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多