Insert into one table from another where the record doesn't already exist

  • I have a table called ptAppointments and a table called ptSchedule.

    We want all records that are in ptSchedule where the ScheduleID is

    not in ptAppointments ID column to be inserted.

    ptSchedule.ScheduleID column is type int and ptAppointments.ID column is type varchar(20)

    {don't ask why}

    Can anyone show me a quick way to do that?

  • Depends on what you mean by "quick":

    Insert into ptApointment(...)

    Select ...

    From ptSchedule s

    Where ScheduleID NOT IN(Select Cast(a.ID as int) from ptApointment a

    Where ISNUMERIC(a.ID))

    I doubt that this will run very fast...

    [font="Times New Roman"]-- RBarryYoung[/font], [font="Times New Roman"] (302)375-0451[/font] blog: MovingSQL.com, Twitter: @RBarryYoung[font="Arial Black"]
    Proactive Performance Solutions, Inc.
    [/font]
    [font="Verdana"] "Performance is our middle name."[/font]

  • This is the general way to do this. Because you did not supply the schemas or clearly define what column in ptAppointments represents ScheduleID I used generic language. If it is ID you may have issues with the implicit conversion. If you do get a conversion error you can use this in the join, A.id Not Like '%[^0-9], which will eliminate non-numerics.

    Insert Into ptAppointments

    (

    column list

    )

    Select

    column list

    From

    dbo.ptSchedule S Left Join

    dbo.ptAppointments A On

    S.pk_key = A.fk_key

    Where

    A.ID is null

  • rbarryyoung (10/28/2008)


    Depends on what you mean by "quick":

    Insert into ptApointment(...)

    Select ...

    From ptSchedule s

    Where ScheduleID NOT IN(Select Cast(a.ID as int) from ptApointment a

    Where ISNUMERIC(a.ID))

    I doubt that this will run very fast...

    or

    insert into ptAppointment(...)

    select ...

    from

    ptSchedule s

    left outer join ptAppointment a

    (s.ScheduleID = cast(a.ID as int))

    where

    a.ID is null;

    Still may not run very fast.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply