Quantcast
Channel: SQLServerCentral » SQL Server 2012 » SQL Server 2012 - T-SQL » Latest topics
Viewing all articles
Browse latest Browse all 4901

Convert single table to parent-child tables.

$
0
0
I have an application and database that I inherited, and am now trying to normalize the database for future application development. Currently, I have a table (Original) that I want to convert over to 2 tables with a parent-child relationship (Parent and Child). This hopefully be a one time import, then I think the proper step is to create a trigger on the Original so that anytime a record is added to the Original table, it also creates the record in the Parent and Child tables.The stucture of the Original table is like:[code="sql"] CREATE TABLE [dbo].Original( SSN [char](9) NOT NULL, FirstName [char](25) NULL, LastName [char](25) NULL, Address [char](30) NULL, City [char](25) NULL, State [char](2) NULL, Zip [char](9) NULL, CONSTRAINT [PK_Original] PRIMARY KEY CLUSTERED ( SSN ))--Test DataINSERT INTO [dbo].[Original] ([SSN] ,[FirstName] ,[LastName] ,[Address] ,[City] ,[State] ,[Zip]) VALUES ('10000001','John', 'Smith', '123 Main', 'Anytown', 'CA', '10000' ) ,('10000002','Jane', 'Smith', '123 Main', 'Anytown', 'CA', '10000' ) ,('999119999','Mary', 'Souza', '546 4th Street', 'Another Town', 'CA', '10001' ) ,('999229999','Mike', 'Jones', '19 Rural Road', 'Anytown', 'CA', '10000' )[/code] I have created 2 new tables:[code="sql"]CREATE TABLE [dbo].[Parent]( [ParentID] [int] IDENTITY(1,1) NOT NULL, [LastName] [varchar](25) NOT NULL, [FirstName] [varchar](25) NOT NULL, Address [varchar](30) NULL, City [varchar](25) NULL, State [char](2) NULL, Zip [char](9) NULL, CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED ( [ParentID] ASC))CREATE TABLE [dbo].[Child]( [ChildID] [int] IDENTITY(1,1) NOT NULL, [ParentID] [int] NOT NULL, --DocumentType will allow for multiple document types, but for this exercise, it will be set to 1 (for SSN in related table) [DocumentType] [int] NOT NULL, [DocumentNumber] [varchar](25) NOT NULL, CONSTRAINT [PK_Child] PRIMARY KEY CLUSTERED ( [ChildID] ASC))[/code]I am having trouble selecting the fields from Original and inserting them into the Parent, then getting the new ParentID, and inserting that into the Child record with the appriate data from Original.My expected results would be like:Original - 100000001, John, Smith, 123 Main, Anytown, CA, 10000 100000002, Jane, Smith, 123 Main, Anytown, CA, 10000 999119999, Mary, Souza, 546 4th Street, Another Town, CA, 10001 999229999, Mike, Jones, 19 Rural Road, Anytown, CA, 10000Parent - 1, Smith, John, 123 Main, Anytown, CA, 100002, Smith, Jane, 123 Main, Anytown, CA, 100003, Souza, Mary, 546 4th Street, Another Town, CA, 100014, Jones, Mike, 19 Rural Road, Anytown, CA, 10000 Child - 1, 1, 1, 1000000002, 2, 1, 1000000013, 3, 1, 9991199994, 4, 1, 999229999 Thank you for your help

Viewing all articles
Browse latest Browse all 4901

Trending Articles