Home Forums SQL Server 2008 T-SQL (SS2K8) multiple columns to single column (normalization) RE: multiple columns to single column (normalization)

  • I don't think your table is normalized. Your have two entities, cars and parts. One car can have several parts, on part can be used in several cars. That's an m:n-relationship. This has to be realized by two 1:n-relationships.

    CREATE TABLE #cars(

    [id] [int] NOT NULL primary key( id )

    ) ON [PRIMARY]

    create table #parts(

    Id int not null

    primary key (id )

    )

    create table #mnPartsCars(

    CarId int not null,

    PartId int not null

    );

    insert into #cars

    SELECT 1 UNION ALL

    SELECT 2 UNION ALL

    SELECT 3 UNION ALL

    SELECT 4 UNION ALL

    SELECT 5

    insert into #parts( Id ) values ( 1 ), ( 2 ), ( 3 );

    insert into #mnPartsCars( CarId, PartId ) values

    ( 1, 1 ),

    ( 1, 2 ),

    ( 1, 3 ),

    ( 3, 2),

    ( 4, 1),

    ( 5, 3);

    select

    CarId = c.id,

    PartId = p.id

    from

    #cars c inner join

    #mnPartsCars mn on

    mn.CarId = c.id inner join

    #parts p on

    p.Id = mn.PartId

    drop table #cars

    drop table #parts

    drop table #mnPartsCars

    There would be two foreign keys on the table #mnPartsCars, one referencing the #Cars-table, one referencing the #Parts-table.