简体   繁体   中英

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

I want to insert (user_id) value from a select statement like below. Can this query will work on both sqlserver and oracle? Kindly advise.

insert into b_user (user_id,
                    user_name,
                    user_email,
                    user_address,
                    user_city,
                    user_state,
                    user_country,
                    user_zip)
values (
   select max(user_id) from b_user ,
   david brown,
   david@david.com,
   chicago,
   il,
   usa,
   60007)

No, that query won't work in either Oracle or SQL Server. You can do an insert based on a select statement, however. Note that you also have to treat strings as strings and enclose them in quotes.

insert into b_user (user_id,
                    user_name,
                    user_email,
                    user_address,
                    user_city,
                    user_state,
                    user_country,
                    user_zip)
   select max(user_id) user_id,
          'david brown',
          'david@david.com',
          'chicago',
          'il',
          'usa',
          '60007'
     from b_user

If we insert bracket () around the SELECT statement, it will work. I tried for SQL Server and it's working for me. Maybe you can try the following query for the Oracle as well.

insert into b_user (user_id,
                    user_name,
                    user_email,
                    user_address,
                    user_city,
                    user_state,
                    user_country,
                    user_zip)
values (
   (select max(user_id) from b_user),
   'david brown',
   'david@david.com',
   '123 davids street',
   'chicago',
   'il',
   'usa',
   60007
)

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