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

守給你的承諾、 提交于 2020-12-15 05:09:33

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/64529792/sqlsql-oracle-insert-value-from-a-select-statement-using-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!