Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

SQL - Mengkloning record dan turunannya

Seperti yang disarankan Martin, Anda harus mengaktifkan IDENTITY_INSERT sehingga Anda dapat mendorong nilai-nilai identitas Anda sendiri. Anda mungkin juga perlu mendapatkan kunci tabel untuk memastikan bahwa Max( Id ) mengembalikan nilai yang benar.

If object_id('tempdb..#TestData') is not null
    Drop Table #TestData
GO
Create Table #TestData
    (
    Id int not null identity(1,1) Primary Key
    , ParentId int not null
    , Name varchar(50) not null
    )
GO
Set Identity_Insert #TestData On
GO  
Insert #TestData( Id, ParentId, Name )
Values( 1,0,'Food' )
    , ( 2,1,'Taste' )
    , ( 3,1,'Price' )
    , ( 4,2,'Taste Requirement' );


With Data As
    (
    Select Cast(MaxId.Id + 1 As int) As Id
        , T.ParentId
        , 'Copy Of ' + T.name As Name
        , T.Id As OldId
        , 0 As OldParentId
    From #TestData As T
        Cross Join( Select Max( id ) As Id From #TestData ) As MaxId
    Where T.Name = 'Food'
    Union All
    Select Cast(Parent.id + Row_Number() Over( Order By Child.Id ) + 1 As int)
        , Parent.Id
        , 'Copy of ' + Child.Name
        , Child.Id
        , Child.ParentId
    From Data As Parent
        Join #TestData As Child
            On Child.ParentId = Parent.OldId
    )
Insert #TestData( Id, ParentId, Name )
Select Id, ParentId, Name
From Data
GO
Set Identity_Insert #TestData Off
GO  

Hasil

id | parentid | name
-- | -------- | -----------------
1  | 0        | Food
2  | 1        | Taste
3  | 1        | Price
4  | 2        | Taste Requirement
5  | 0        | Copy Of Food
7  | 5        | Copy of Taste
8  | 5        | Copy of Price
9  | 7        | Copy of Taste Requirement


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Tambahkan warna baris bergantian ke laporan layanan Pelaporan SQL Server

  2. Mengapa SQL Server mengabaikan ruang kosong di akhir secara otomatis?

  3. VMware CPU Hot Plug vNUMA Effects pada SQL Server

  4. Kueri Pohon SQL Server

  5. Peningkatan indeks otomatis untuk Microsoft SQL Server 2008 R2