SQL(SQL/Oracle) 使用序列从选择语句插入值

2021-09-10 00:00:00 sql tsql oracle sql-server

我想从如下所示的 select 语句中插入 (user_id) 值,而没有标识列.目前这个查询没有按顺序跟随序列号.请指教.

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&8047fiddlee=195728e48cc8a5a0047fec8837e9f217一个>

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

推荐答案

这是在回答问题的原始版本.

如果您问是否可以使用相同的 SQL 语句在 SQL Server 和 Oracle 中使用序列,那么,不,您不能.

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

在 Oracle 中,语法为:

In Oracle, the syntax is:

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

在 SQL Server 中,语法为:

In SQL Server, the syntax is:

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


在 Oracle 中,您可以将对该序列的调用包装在一个函数中:


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;
/

然后你可以使用:

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

但是,在 SQL Server 您不能在用户中使用序列-定义了函数,因此无法复制 Oracle 中的方法.

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

所以,简而言之,如果您使用序列,您将不得不对不同的数据库使用不同的 SQL 语句.

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

如果您想使用 IDENTITY 列,那么您可以在两者中获得相同的语法.

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

在甲骨文中:

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)
);

在 SQL Server 中:

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 和 SQL Server db<>fiddle

相关文章