|
-
Sep 16th, 2019, 04:13 AM
#1
Thread Starter
Frenzied Member
[RESOLVED] Insert a child record for every existing parent ID
Hi,
I have in the database tblUsers:
UserID
LastName
FirstName
etc.
I now created another table tblUserSettings:
UserSettingID
UserID
Setting1
Setting2
etc.
So every user shall have some settings that I can use all over. e.g. I want to create 3 color themes, etc.
The problem that I now have is that this newly created tblUserSettings is empty and I have a lot of existing UserID's. I want to insert default (child) data for every existing UserID in tblUsers.
Meaning for every UserID in tblUsers insert default values to tblUserSettings.
This is a one time problem because in the future when a new user is created in tblUsers then I shall insert a record with default values for that user in tblUserSettings.
I guess I can do this manually, but it will a pain as it will take long time and maybe i can learn a quick way for future scenarios like this.
Thank you
-
Sep 16th, 2019, 05:42 AM
#2
Re: Insert a child record for every existing parent ID
Something like:
insert into tblUserSettings(UserID,Setting1,Setting2,....)
select distinct UserID, 'default1','default1',....)
from tblUsers
With the default values hardcoded like 'red','blue' or 1,2,3
Please remember next time...elections matter!
-
Sep 20th, 2019, 07:32 AM
#3
Re: Insert a child record for every existing parent ID
A slightly modified version from Tyson where in the event this needed to be ran more than once the following ensures no duplicates. Also note the setting table should have a primary key.
Code:
INSERT INTO tblUserSettings ( UserID )
SELECT UserID
FROM dbo.tblUsers t1
WHERE t1.UserID NOT IN ( SELECT UserID
FROM dbo.tblUserSettings );

Defining SQL in code
Code:
Dim insertIntoStatement As String =
<SQL>
INSERT INTO tblUserSettings ( UserID )
SELECT UserID
FROM dbo.tblUsers t1
WHERE t1.UserID NOT IN ( SELECT UserID
FROM dbo.tblUserSettings );
</SQL>.Value
-
Sep 20th, 2019, 09:43 AM
#4
Re: Insert a child record for every existing parent ID
I'd have gone with a left join
Code:
INSERT INTO tblUserSettings ( UserID, Setting1, Setting2, Setting3)
SELECT U.UserID, 'S1', 'S2', 'S3'
FROM dbo.tblUsers U
LEFT JOIN dbo.tblUserSettings US on U.UserID = US.UserID
WHERE US.UserID is null
Just another way to skin the cat.
-tg
-
Sep 20th, 2019, 10:05 AM
#5
Thread Starter
Frenzied Member
Re: Insert a child record for every existing parent ID
How do you all just KNOW these things!!!
Thank you very much
-
Sep 20th, 2019, 11:31 AM
#6
Re: Insert a child record for every existing parent ID
 Originally Posted by schoemr
How do you all just KNOW these things!!!
Thank you very much 
The same way one gets to Carnegie Hall... Practice, practice, practice.
-tg
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|