怎样用sql语句复制表table1到表table2的同时复制主键

时间:2022-06-26 07:29:10

原文: 怎样用sql语句复制表table1到表table2的同时复制主键

在从table1表复制到table2的时候,我们会用语句:

select * into table2 from table1
  

但这个语句并不能在复制数据的同时,复制主键。


下面的代码通过动态语句,来实现在复制数据的同时,也会复制主键:



   
  
  1. if OBJECT_ID(‘table1‘) is not null
  2. drop table table1
  3. go
  4. create table table1
  5. (
  6. id int ,
  7. idd int,
  8. vvv varchar( 100),
  9. primary key ( id,idd) --为了实验在主键有多个字段的情况,所有主键这里有2个字段
  10. )
  11. insert into table1
  12. select 1, 1, ‘a‘ union all
  13. select 1, 2, ‘b‘ union all
  14. select 2, 1, ‘a‘
  15. go
  16. declare @old_table_name varchar( 30)
  17. declare @new_table_name varchar( 30)
  18. declare @is_clustered varchar( 10)
  19. declare @ sql varchar( 1000)
  20. set @old_table_name = ‘table1‘;
  21. set @new_table_name = ‘table2‘;
  22. set @is_clustered = ‘‘;
  23. set @ sql = ‘‘;
  24. select @is_clustered = i.type_desc,
  25. @ sql = @ sql ‘,‘ c.name
  26. case when ic.is_descending_key = 0
  27. then ‘ asc‘
  28. else ‘ desc‘
  29. end
  30. from sys.tables t
  31. inner join sys.indexes i
  32. on t.object_id = i.object_id
  33. inner join sys.index_columns ic
  34. on i.object_id = ic.object_id
  35. and i.index_id = ic.index_id
  36. inner join sys.columns c
  37. on c.column_id = ic.column_id
  38. and c.object_id = ic.object_id
  39. where i.is_primary_key = 1
  40. and t.name = @old_table_name
  41. order by key_ordinal
  42. select @ sql = ‘if object_id(‘‘‘ @new_table_name ‘‘‘) is not null‘
  43. ‘ drop table ‘ @new_table_name ‘;‘
  44. ‘select * into ‘ @new_table_name
  45. ‘ from ‘ @old_table_name ‘;‘
  46. ‘alter table ‘ @new_table_name
  47. ‘ add primary key ‘ @is_clustered
  48. ‘(‘ stuff(@ sql, 1, 1, ‘‘) ‘)‘
  49. select @ sql
  50. /*
  51. if object_id(‘table2‘) is not null
  52. drop table table2;
  53. select * into table2 from table1;
  54. alter table table2 add primary key CLUSTERED(id asc,idd asc)
  55. */
  56. exec(@ sql)
  57. select *
  58. from table2
  59. /*
  60. id idd vvv
  61. 1 1 a
  62. 1 2 b
  63. 2 1 a
  64. */


怎样用sql语句复制表table1到表table2的同时复制主键怎样用sql语句复制表table1到表table2的同时复制主键 不想长大啊 发布了416 篇原创文章 · 获赞 135 · 访问量 94万 他的留言板 关注