SQL - Copy Data Within Same Table

前端 未结 4 468
谎友^
谎友^ 2021-01-16 19:58

I\'m not that great with SQL Server, but I\'m trying to do some behind the scenes work to create some functionality that our EMR system lacks - copying forms (and all their

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 20:40

    declare @oldEncounterID int
    set @oldEncounterID = 1234
    
    declare @newEncounterID int
    set @newEncounterID = 2345
    
    insert into table1(encounter_id, patient_id, date, time, etc)
    select newEncounterID, patient_id, date, time, etc
    from table1 where encounter_id = oldEncounterID
    

    and so on... problem with this approach you must know in advantage what all the columns are, and if they change you may change the columns accordingly

    Another approach:

    declare @oldEncounterID int
    set @oldEncounterID = 1234
    
    declare @newEncounterID int
    set @newEncounterID = 2345
    select * into #table1 from table1 where encounter_id = oldEncounterID
    update #table1 set encounter_id = newEncounterID
    insert into table1 select * from #table1
    

    and so on... this second approach however may need a little adjustment if there is an identity column then you'll have to set identity_insert to on

提交回复
热议问题