数据库表间数据复制

来源:互联网 发布:半自动覆膜机分切数据 编辑:程序博客网 时间:2024/05/20 07:59
数据库表间数据复制
      在利用数据库开发时,常常会将一些表之间的数据互相导入。当然可以编写程序实现,但是,程序常常需要开发环境,不方便。最方便是利用sql语言直接导入。既方便而修改也简单。以下就是导入的方法。

1。表结构相同的表,且在同一数据库(如,table1,table2)

Sql :insert into table1 select * from table2 (完全复制)

           insert into table1 select distinct * from table2(不复制重复纪录)

          insert into table1 select top 5 * from table2 (前五条纪录)

2。   不在同一数据库中(如,db1 table1,db2 table2)

sql:    insert into db1..table1 select * from db2..table2 (完全复制)

           insert into db1..table1 select distinct * from db2table2(不复制重复纪录)

          insert into tdb1..able1 select top 5 * from   db2table2 (前五条纪录)

3.      表结构不同的表或复制部分纪录(如,dn_user,dn_user2)

a.    建一个新表[DN_UserTemp](在老表dn_user上增加一列)

CREATE TABLE [DN_UserTemp] ( [Num] [numeric](18, 0) IDENTITY (1, 1) NOT NULL)
[Id] [idtype] NOT NULL ,
[Name] [fntype] NOT NULL ,
[Descript] [dstype] NULL ,
[LogonNm] [idtype] NOT NULL ,
[Password] [idtype] NULL ,
[Gender] [char] (1) NULL ,
[Quited] [booltype] NOT NULL,
[OffDuty] [booltype] NOT NULL ,
[Stopped] [booltype] NOT NULL,
[OSBind] [booltype] NOT NULL,
[Domain] [idtype] NULL ,
[EMail] [fntype] NULL ,
[UnitId] [idtype] NULL ,
[BranchId] [idtype] NULL ,
[DutyId] [idtype] NULL ,
[LevelId] [idtype] NULL ,
[ClassId] [idtype] NULL ,
[TypeId] [idtype] NULL ,
[IP] [varchar] (15) COLLATE Chinese_PRC_CI_AS NULL ,
[ExpireDT] [datetime] NULL ,
[Sort] [int] NOT NULL ,
[AllowDel] [booltype] NOT NULL,
[UnitChief] [booltype] NOT NULL,
[BranchChief] [booltype] NOT NULL ,
[UnitDeputy] [booltype] NOT NULL ,
[BranchDeputy] [booltype] NOT NULL ,
     
        [Num] [numeric](18, 0) IDENTITY (1, 1) NOT NULL

) ON [PRIMARY]

b. 将dn_uer2的数据拷入dn_usertemp

sql:insert into dn_usertemp select * from dn_user2

c.将dn_usertemp 拷入dn_user

sql:

declare @i int
declare @j int
declare @Name fntype
set @i=1
select @j=count(*) from dn_usertemp
while @i<@j 1
begin

select @Name=Name from dn_usertemp where Num=@i
print @Name
insert into dn_user (Name) values (@Name) where
Num=@i
select @i=@i 1
end

---------------------------

creat到--

然后把数据库名改成想复制到的那个库的名称

 

精妙的SQL语句收藏
说明:复制表(只复制结构,源表名:a 新表名:b)
select * into b from a where 1<>1
  • 说明:拷贝表(拷贝数据,源表名:a 目标表名:b)
    insert into b(a, b, c) select d,e,f from b;
    说明:日程安排提前五分钟提醒
    select * from 日程安排 where datediff('minute',f开始时间,getdate())>5
    说明:两张关联表,删除主表中已经在副表中没有的信息
    delete from info where not exists ( select * from infobz where info.infid=infobz.infid )
    说明:清除表中重复的记录(PriKey为递增值主键,key为判断相同记录的标准)
    Delete From B Where B.PriKey In(Select B.PriKey from B As s1 Where B.PriKey not in (Select max(B.PriKey) from B As s2 Where s1.key=s2.key))
  • 原创粉丝点击