简体   繁体   English

如何将 T-SQL 查询转换为连接子字符串的 PostgreSQL?

[英]How do I convert a T-SQL query to PostgreSQL that concatenates substrings?

This is my query:这是我的查询:

SELECT
    *,
    CONCAT(
        RIGHT( account_no, 4),
        RIGHT( customer_id, 5 )
    ) AS "password for my diplomo"
FROM
    account_info;

But I get this error:但我得到这个错误:

Error: function left(bigint, integer) does not exist;错误:function left(bigint, integer)不存在;

My table is:我的桌子是:

CREATE TABLE account_info (
    account_no  bigint       NOT NULL PRIMARY KEY,
    customer_id varchar(...)
)

You seem to be using a reference for T-SQL or JET Red SQL (for MS SQL Server and MS Access respectively) when you're actually using PostgreSQL which uses completely different functions (and syntax) for string/text processing.当您实际使用 PostgreSQL 时,您似乎正在使用 T-SQL 或 JET Red SQL 参考(分别用于 MS SQL 服务器和 MS Access)。

This is the PostgreSQL v12 manual page for string functions and other syntax.这是字符串函数和其他语法的 PostgreSQL v12 手册页。 You should read it .你应该阅读它

As for making your query run on PostgreSQL, change it to this:至于让您的查询在 PostgreSQL 上运行,请将其更改为:

  • Convert account_no to a varchar type so you can use SUBSTRING with it.account_no转换为varchar类型,以便您可以使用SUBSTRING

    • I think it might work without it, but I don't like relying on implicit conversion, especially when localization/locale/culture issues might pop-up.我认为没有它它可能会工作,但我不喜欢依赖隐式转换,尤其是当本地化/语言环境/文化问题可能会弹出时。
  • The LEFT and RIGHT functions for extracting substrings can be reimplemented like so:用于提取子字符串的LEFTRIGHT函数可以重新实现,如下所示:

     LEFT( text, length ) == SUBSTRING( text FROM 0 FOR length ) RIGHT( text, length ) == SUBSTRING( text FROM CHAR_LENGTH( text ) - length )
  • And use ||并使用|| to concatenate text values together.将文本值连接在一起。

Like so:像这样:

SELECT
    q.*,
    (
        SUBSTRING( q.account_no_text FROM CHAR_LENGTH( q.account_no_text ) - 4 )
        ||
        SUBSTRING( q.customer_id FROM CHAR_LENGTH( q.customer_id ) - 5 )
    ) AS "password for my diplomo"
FROM
    (
        SELECT
            ai.*,
            ai.account_no::varchar(10) AS account_no_text
        FROM
            account_info AS ai
    )
        AS q

Here is a runnable DB-Fiddle.这是一个可运行的 DB-Fiddle。

Screenshot proof:截图证明:

在此处输入图像描述

Postgres functions left and right expect their first argument be text . Postgres函数leftright期望它们的第一个参数是text So first cast account_no to type text and your query (a bit simplified) will work.因此,首先将account_no转换为输入text ,然后您的查询(有点简化)将起作用。

SELECT *,
       right(account_no::text, 4) || right(customer_id, 5) as pfmd
FROM account_info;

Unrelated but the best practice under Postgres is to use type text instead of char or varchar .不相关但 Postgres 下的最佳实践是使用类型text而不是charvarchar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM