Jump to content

Inserting multiple rows in one statement with different variables?


homiee
 Share

Recommended Posts

Hello everybody,Assume I have this table called "Messages":MSGID (PK, Auto-Increment) | UID(Int32) | Body(TEXT)------------------------------------------------1 | 20 | Hello what's up user 202 | 21 | Hello what's up user 21In order to insert a single row (or Message):INSERT INTO Messages(UID, Body) VALUES(20, "Have a good morning user 20")This would insert a Message to User 20 with the message body "Have a good morning ... "What if I want to Insert a message (same message) for more users at one single Insert statement? Assuming I have a comma-seperated string containing all the UIDs of the users I want to add a message to? is it even possible?Thanks in advance,homiee

Link to comment
Share on other sites

Hello everybody,Assume I have this table called "Messages":MSGID (PK, Auto-Increment) | UID(Int32) | Body(TEXT)------------------------------------------------1 | 20 | Hello what's up user 202 | 21 | Hello what's up user 21In order to insert a single row (or Message):INSERT INTO Messages(UID, Body) VALUES(20, "Have a good morning user 20")This would insert a Message to User 20 with the message body "Have a good morning ... "What if I want to Insert a message (same message) for more users at one single Insert statement? Assuming I have a comma-seperated string containing all the UIDs of the users I want to add a message to? is it even possible?Thanks in advance,homiee
Use INSERT...SELECT syntax. Assuming you have a Messages table and a Users table.
INSERT INTO Messages(UID, Body)SELECT UID, 'Have a Good morning, user' + UID From Users where UID IN (@list_of_users)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...