要将库表导入到另外一个服务器上,库表结构和数据都导入成功,但是约束(主键和自动增长标识)丢失,最终在库中建立游标解决了,模拟代码如下:
use master
go
if exists(select * from sysdatabases where name='mytest')
drop database mytest
go
create database mytest
go
use mytest
go
create table user1
(
mid int ,
name varchar(25)
)
go
create table user2
(
mid int,
name varchar(25)
)
go
select * from user1
select * from user2
--drop table user1
--drop table user2
--*****start*****--
DECLARE @table_name sysname --保存表名的全局变量
-- 获得所有User表
DECLARE tables_cursor CURSOR FOR select name from sysobjects where xtype='U' and status>0 --(加入这个条件是因为前面的条件查询出来的结果带有"dtproperties"非用户所建的表,应该还有其他滤去该表的条件)
OPEN tables_cursor
-- Perform the first fetch
FETCH NEXT FROM tables_cursor INTO @table_name
-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
-- 遍历表@table_name的每条记录
-- 动态生成执行语句
exec ( 'alter table '+ @table_name+' drop column mid ' )
exec ('alter table '+ @table_name +' add mid int primary key IDENTITY(1,1) ')
FETCH NEXT FROM tables_cursor INTO @table_name
END
CLOSE tables_cursor --CLOSE语句关闭已打开的游标,之后不能对游标进行读取等操作,但可以使用OPEN语句再次打开该游标
DEALLOCATE tables_cursor --DEALLOCATE语句删除定义游标的数据结构,删除后不可再用
(关于DEALLOCATE:http://www.yesky.com/imagesnew/software/tsql/ts_de-dz_7vxh.htm)
--*****end*****--