简体   繁体   中英

SQL(SQL/Oracle) insert value from a select statement using sequence

I want to insert (user_id) value from a select statement like below without identity column. Currently this query doesn't follow the sequence number in order. Kindly advise.

https://dbfiddle.uk/?rdbms=oracle_18&fiddle=195728e48cc8a5a0047fec8837e9f217

This is answering the original version of the question.

If you are asking can you have identical SQL statements to use a sequence in SQL Server and in Oracle then, no, you cannot.

In Oracle, the syntax is:

INSERT INTO b_user ( user_id /*, ... */ )
  VALUES ( b_user__user_id__seq.NEXT_VAL /*, ... */ );

In SQL Server, the syntax is:

INSERT INTO b_user ( user_id /*, ... */ )
  VALUES ( NEXT VALUE FOR b_user__user_id__seq /*, ... */ );

In Oracle, you could wrap the call to the sequence in a function:

CREATE FUNCTION get_next_b_user_id RETURN INT
IS
BEGIN
  RETURN b_user__user_id__seq.NEXTVAL;
END;
/

Then you could use:

INSERT INTO b_user ( user_id /*, ... */ )
  VALUES ( get_next_b_user__id__seq() /*, ... */ );

However, in SQL server you cannot use a sequence in user-defined functions so that approach in Oracle cannot be replicated.


So, in short, you are going to have to use different SQL statements for the different databases if you are using a sequence.

If you want to use an IDENTITY column then you can get the same syntax in both.

In Oracle:

CREATE TABLE b_user (
  user_id      INT
               GENERATED ALWAYS AS IDENTITY,
  user_name    VARCHAR(250),
  user_email   VARCHAR(250),
  user_address VARCHAR(250),
  user_city    VARCHAR(50),
  user_state   VARCHAR(5),
  user_country VARCHAR(5),
  user_zip     VARCHAR(10)
);

and in SQL Server:

CREATE TABLE b_user (
  user_id      INT IDENTITY(1,1),
  user_name    VARCHAR(250),
  user_email   VARCHAR(250),
  user_address VARCHAR(250),
  user_city    VARCHAR(50),
  user_state   VARCHAR(5),
  user_country VARCHAR(5),
  user_zip     VARCHAR(10)
)

Then, in both databases, you can use the statement:

insert into b_user (
  user_name,
  user_email,
  user_address,
  user_city,
  user_state,
  user_country,
  user_zip
) values (
  'Alice',
  'alice@example.com',
  'A house',
  'A city',
  'STATE',
  'ABC',
  'ZZ0123'
);

Oracle db<>fiddle and SQL Server db<>fiddle

one option is, if you know know that the column user_id has some values already inserted then when you create a sequence which you are going to use for that column

--example you start with 3 if you know 2 is the maximum value for that column.
CREATE SEQUENCE b_user__user_id__seq  start with 3 ;

It is better to have a primary key or unique constraint in that column.

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