views:

45

answers:

2

I have two separate tables used for categories.

One is Categories(ID, Title, Description), and the other is SubCategories(ID, UpperID, Title, Description)

I want to insert the records from categories to SubCategories with upperID=0. I've looked at SQL SELECT INTO but don't know how to use it for existing tables.

+5  A: 
Insert Into dbo.SubCategories (UpperId, Title, Description)

Select 0, Title, Description
From dbo.Categories

This assumes that the ID column in both tables is an Identity column and that the ID in Categories should not be transferred to the SubCategories table

Barry
adding to the answer, if you want to pass the ID as well (*and it is non-conflicting with existing keys*) use the `SET IDENTITY_INSERT SubCategories ON`
Gaby
I was going to add this in but as I'm not 100% sure what the OP wants I decided to leave it out to avoid confusion. Still a good point to make though.
Barry
Used: INSERT INTO dbo.Categories (UpperId, Title, Description) SELECT UpperID, Title, Description FROM dbo.SubCategories; Because subcategories had ID's from categories so now I don't need to change catID's :)
HasanGursoy
A: 
INSERT INTO SubCategories(ID, UpperID, Title, Description)

SELECT ID, 0, Title, Description FROM Categories

assuming that Id is not Identity field.

Azhar
-, this will give you an error with mssql ...! take a look at barry's answer (which has correct syntax)
Andreas Niedermair
NO... if you are talking about Identity then I have explained about it.
Azhar
nope... it's not about identity ... it's just your invalid syntax: `INSERT INTO TABLE (Column1, Column2, ...) VALUES (SubSelect)` is not valid. it must state `INSERT INTO TABLE (Column1, Column2, ...) SubSelect`
Andreas Niedermair
removed downvote...
Andreas Niedermair