問題描述
我想從如下所示的 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
這篇關于SQL(SQL/Oracle) 使用序列從選擇語句插入值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!