Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a row for all the rows in another table in SQL Server

I am not the best at the SQL language. I have a table with approximately 20,000 users (rows) in it. I have another table, that I would like to add a row to for every user, using their username. Is this possible using only SQL?

I could just go into the application (written in c#) and use linq to pull out all the users, iterate over them, and add a row for each user. I'm just curious if there is a way to do it in SQL directly.

TABLE Users
Username (varchar)
etc
etc

TABLE ChatChannels
Username (varchar)
ChannelName (varchar)

I would like to add one row in ChatChannels for every user in Users, using the username to populate the Username column in ChatChannels.

like image 735
Chev Avatar asked Feb 08 '11 19:02

Chev


People also ask

How do we add rows from one table to another?

For example, to insert two rows above a row, first select two rows in your table and then click Insert Above.

How do I combine multiple rows into one in SQL Server?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do I insert the same data in multiple rows?

Select all the cells where you want to enter the same data Put the cursor to the first cell in the column (or the second one if your Table has headers), then press Shift+Ctrl+End to go to the end of your table, hold Shift and press the Left key repeatedly until only the needed column gets selected.


1 Answers

insert into chatchannels (Username, ChannelName)
select username, 'NewChatChannel'
from users

This inserts one row per username in users, with the channelname set to 'NewChatChannel'.

like image 145
RichardTheKiwi Avatar answered Sep 26 '22 02:09

RichardTheKiwi