Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Insert rows using CTE

Status
Not open for further replies.

yorge

Programmer
Aug 2, 2011
39
PH
Hi Guys,

Given sample tables below:

CREATE TABLE [dbo].[TBL1](
[ID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[ITEM_CODE] [varchar](20) NOT NULL,
[CREATED_DATETIME] [datetime] NOT NULL
);

CREATE TABLE [dbo].[TBL2](
[ID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[TBL1ID] [int] NOT NULL,
[DESC] [varchar](50) NOT NULL DEFAULT 'TBL2 DESC',
[CREATED_DATETIME] [datetime] NOT NULL
);

CREATE TABLE [dbo].[TBL3](
[ID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[TBL2ID] [int] NOT NULL,
[DESC] [varchar](50) NOT NULL DEFAULT 'TBL3 DESC',
[CREATED_DATETIME] [datetime] NOT NULL
);

SAMPLE TBL1 DATA:

INSERT INTO TBL1 VALUES ('SERVER1', getdate());
INSERT INTO TBL1 VALUES ('SERVER2', getdate());
INSERT INTO TBL1 VALUES ('SERVER3', getdate());
INSERT INTO TBL1 VALUES ('SERVER4', getdate());
INSERT INTO TBL1 VALUES ('SERVER5', getdate());


WHERE:

TBL2.TBL1ID = TBL1.ID
TBL3.TBL2ID = TBL2.ID

Assuming TBL1 contains data, is there a way to be able to INSERT rows on TBL2 and TBL3 using CTE?
If not possible, what other means of inserting the rows without using CURSOR.

Im using MSSQL server 2012

TIA,
yorge
 
CTE meaqns common table expression and is generally used to define a query (SELECT) and name it, as if there was a table by that name, it's not used for INSERTs.

If you want data of TBL1 in TBL2, you do [tt]INSERT INTO TBL2 SELECT * FROM TBL1[/tt], in general a more precise query in regard of what fields to copy over. With typical table relations in 4NF you just copy the primary key over as foreign key into further tables to let them point to the same data and NOT copy it. If you want something else, then please sepcify what your goal is, I also don't understand what your mentioning of the relations of TBL2 to TBL1 and TBL3 to TBL2 are all about, but this might play a role in what I said about relations.

Bye, Olaf.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top