sql语句 怎么从一张表中查询数据插入到另一张表中? sql语句 怎么从一张表中查询数据插入到另一张表中?

 ----原文地址:http://www.phpfans.net/ask/MTc0MTQ4Mw.html
比如我有两张表

table1 字段 uname,age,address,school,

table2 字段 stuname,address.


1、我想把从table2中查询出数据插入到table1中,而且我想插入时加入一些默认数据,改怎么写呢,

如: insert into table1(uname,address,school) values(name 和address 从table2中查,school是一个固定值)


2、怎么通过sql语句访问另一个数据库中的某个表呢?
 
 
SQL code
insert into table1(uname,address,school) select name,address,'北京大学' from table2
2、
SQL code
use A go select * from B..tb --B库tb表,从A库查!
 
 
 
SQL code
insert into table1(uname,age,address,school) select stuname,[age的默认值],address,[school的默认值] from table2


2、怎么通过sql语句访问另一个数据库中的某个表呢?
--> 先建LinkServer, 访问时用[LinkServer名].[数据库名].[架构名].[Table名]
 
 
 
SQL code
--1,insert into table1 select name,'固定值',address,'固定值' from table2 --2select * from 库名.dbo.表名
 
 
 
1:school的值可以手动填写进去 或者在建表的时候直接设置默认值
2:本机数据的的访问select * from数据库名.dbo.表名
跨服务器连接数据库要通过
exec sp_addlinkedserver....
exec sp_addlinkedsrvlogin....
具体看个人怎么需求了
 
 
 
SQL code
1, select * into table1 from (select col1 ,cal2 from table2 ) a 2, exec sp_configure 'show advanced options',1; --设置其它选项应先开启这个选项,最先开启,最后关闭。reconfigure; exec sp_configure 'Ad Hoc Distributed Queries',1; --记得使用完后一定要关闭。reconfigure; select * from openrowset( 'SQLOLEDB ', '192.168.0.2'; 'sa'; 'szonline.net',[CCEasy].dbo.[city])