简体   繁体   中英

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;

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.

This is the PostgreSQL v12 manual page for string functions and other syntax. You should read it .

As for making your query run on PostgreSQL, change it to this:

  • Convert account_no to a varchar type so you can use SUBSTRING with it.

    • 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:

     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.

Screenshot proof:

在此处输入图像描述

Postgres functions left and right expect their first argument be text . So first cast account_no to type text and your query (a bit simplified) will work.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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