1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

文字列と10桁の採番された番号+1の値を求めるSQL

Posted at

準備

PostgreSQL 12
Windows 11

create table public.a (
  b character varying(14)
  , c character varying(15)
);

INSERT 
INTO public.a(b, c) 
VALUES ('RES_0000000001', 'ニワトリ')
, ('RES_0000000002', 'オカメインコ')
, ('RES_0000000003', 'ネコ')
, ('RES_0000000004', 'イヌ'); 

SQL

・SUBSTRING関数と正規表現 'RES_(\d+)' を使って "RES_" に続く数値部分を抽出します。
・CAST関数で抽出した数値部分を bigint 型に変換します。
・MAX関数で最大値を求め、1を加えます。
・LPAD関数を使って得られた数値を10桁になるまで左側から0で埋めます。
・|| 演算子で新たな最大値の先頭に "RES_" を付けます。

SELECT
    'RES_' || LPAD( 
        CAST( 
            ( 
                MAX(CAST(SUBSTRING(b FROM 'RES_(\d+)') AS bigint)) + 1
            ) AS character varying
        ) 
        , 10
        , '0'
    ) AS Next_b 
FROM
    public.a;

SQL実行後の値

RES_0000000005
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?