新建表或者复制表,从另一个表得到记录.

//------该表不存在将PrintDb.dbo.tb_login中的记录插入到 db_MyExam 数据库的 tb_login中.(注意: 该表不存在)
use db_MyExam
go
  select * INTO tb_login from printDB.dbo.tb_login 
  go
  


//----------如果表2已经存在,把表1中的记录加到表2中的语句:------------------------------ 
  insert into 表2 (字段1,字段2,...) select 字段1,字段2,.. from 表2 where ...  
   
insert into  tb_bkCodes  select * from codes where id = 45


insert into [customs].[dbo].[tb_Balance] (ph1,[ph2],[ph3],[ph4] ) select [ljmx5],[ljmx3],[ljmx7],[ljmx9]  FROM [customs].[dbo].[tb_ljMx]


  如果表2不存在,则用下面的语句会自动生成表2,字段的类型和表1一样:  
  select 字段1,字段2,.. INTO 表2 from 表1 where ... 


 insert into [customs].[dbo].[tb_Balance] select *  FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0', 'Data Source="D:\All_doc\Document_Setting\系统软件类\关务核销系统\customsDB.mdb";User ID=Admin;Password=;Jet OLEDB:Database Password=')...tb_Balance




------------------------插入记录至userpope--------------------------------------
use DB_HRMS_TEST
go


 --- insert into 表(字段,字段,...) select 字段,字段,.. from 表where ...  
 
 insert into DB_HRMS_TEST.[dbo].tb_UserPope (ID,PopeName, Pope ) SELECT ID,PopeName,Pope from db_PWMS.dbo.tb_UserPope
 go
 
  
-----------------------------------以下将产生错误---------------------
 insert into DB_HRMS_TEST.[dbo].tb_UserPope (AutoID,ID,PopeName, Pope ) SELECT AutoID, ID,PopeName,Pope from db_PWMS.dbo.tb_UserPope
 go




autoid 是自增长列,所以会出现这样的错误提示.


--------------从另一个数据库表记录复制到现有数据库表中-----------------------------
tb_login 表
insert into DB_HRMS_TEST.dbo.tb_Login (id,Name, Pass)  SELECT ID, [Name],[Pass]  FROM [db_PWMS].[dbo].[tb_Login]
tb_popeModel表
     insert into DB_HRMS_TEST.dbo.tb_PopeModel ( PopeName) SELECT  [PopeName]  FROM [db_PWMS].[dbo].[tb_PopeModel]
(id为主键,并且自增长的.)


-------------------------------------------------------------------------------------------------
/****** Script for SelectTopNRows command from SSMS  ******/
use customs 
go 
/***数据库不存在则插入用....select * into ....**********************/
---有表则用insert into tb_BanlanceXhHz
select  
 
 [ph2] [项号]
,SUM([ph5]) [期初数(A)]
,SUM(ph6) [原料进口(b)]
,SUM(ph7)  [成品出口(C)]
,SUM(ph8)  [理论剩余(E=A+B-C)]
,SUM(ph9) [企业原料实盘数(F)]
,SUM(ph10) [企业原料不良数(F1)]
,SUM(ph11)  [在库成品折料(G)]
,SUM([ph12]) [在库半成品折料(H)]
,SUM(ph13) [实际剩余(I=F+F1+G+H)]
,SUM(ph14) [理论与实际差异(J=E-I)]
,SUM(ph15) [美金单价]
,SUM(ph16) [美金总价]
,SUM(ph17) [折合人民币]
,SUM(ph18) [关税率]
,SUM(ph19) [增值税率]
,SUM(ph20) [关税]
,SUM(ph21) [增值税]
,SUM(ph22) [预估税金]


into tb_BanlanceXhHz 


FROM [customs].[dbo].[tb_Balance] group by ph2  order by ph2 


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


你可能感兴趣的:(新建表或者复制表,从另一个表得到记录.)