简体   繁体   中英

Insert multipe rows for the same value - SQL

How can I insert more than one row for the same value for example, each user has to submit 2 forms so the username is the same in each form but the information is different

I tried to use UPDATE but it removes the ole information and replaces it with the new one while I want to keep both

is there a way to do that?

insert into your_table (username, col2)
values ('user1', 1),
       ('user1', 2)

you can add duplicate data just your primary key can't be duplicated because it causes primary key constraint. so what you can do is have an extra column let's say "ID" make it your primary key. While submitting the row keep on adding ID column's value by one, rest of the data could be same.

Use below insert format to get your desired result:

insert into Table_name(Field1, Field2)
SELECT 'user_1', 1 UNION ALL
SELECT 'user_1', 2

It depends on whether your USERNAME column allows duplicates.

If it's the primary key of the table, your table schema doesn't support what you want to do, because PK should be UNIQUE.

If your USERNAME column allows duplicates, you can use INSERT:

 declare @username varchar(max) = 'your_username' --declare a variable to use the same username

 insert into table_name (username, form_data)
 values(@username, 'form_data_1')
      ,(@username, 'form_data_2')

It also depends on how you're executing the SQL statement. I would definately go and create stored procedure to do this insert.

Have two tables, 'USERS' and 'FORMSUBMISSIONS'

When a user submits a form for the first time, a new entry is created in the USERS table, which is unique for each user, and would contain information connected to the user.

And whenever a form is submitted (including the first time), an entry is written to the FORMSUBMISSIONS table with the details of that submission, and a foreign key back to USERS.

That's a cleaner data model for this situation. It will also help future queries on the data. If you are limited to a single table for some reason, then successive inserts will work as above, as long as there is no unique key on the USER field.

you can use bulk insert query for that. as suggested by @huergen but make sure that your username or any field that might be in form data does not have UNIQUE key index. you can also add another field that works like PRIMARY key in that table.so many ways to do but it depends upon your requirement.

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