Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query to INSERT new data from existing table

Author  Topic 

scholin
Yak Posting Veteran

56 Posts

Posted - 2010-06-09 : 02:11:19
I have a table called dbo.results that is used as a lookup table for my clients. The set of lookup items is specific to each user.

When I sign on a new user, I want to run a query that will copy a set of default item where default=true, INSERT them into the same table but with the new user_id field (so I don't have to manually have to recreate about 15 new rows of data).

So how can I write an INSERT query to copy the entire rows of existing data from dbo.results where default=true and add the new users_id=X, adding these new rows to the same table - dbo.results?

Thank!

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-06-09 : 02:20:23
If there is already a user with all default values in the table:
insert result
select @new_user_id, col1, col2, ... from result
where user_id=<existing_user_id> and default='true'

Else
insert result
select DISTINCT @new_user_id, col1, col2, ... from result
where default='true'



No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

scholin
Yak Posting Veteran

56 Posts

Posted - 2010-06-09 : 12:55:16
Thank you for your response Webfred.

Question: I am not sure what the IF statement is for if I want to run a single query. But after giving this more thought I would like to dig a bit deeper.

To make this a bit more clear and using your example:
I will use a default user_ID=9999 (this will be associated with default rows that I want to use for each new user. So I will select user_ID 9999 to copy those rows and manually type into the query the new user_id and run the query to insert the new rows with the only difference being the new user_id.

Does that change how you would write this?

thanks for the help, sorry for the basic question.
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-06-09 : 13:30:39
Yes you are right.
Instead of @new_user as a variable you can type in the new user_id.

The IF and ELSE are NOT SQL-STATEMENTS in my post.
I just wanted to give you two possible ways.


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page
   

- Advertisement -