oracle 导sqlserver 主键不会自动导过去

我采用以下方式查询所有的主键及联合主键,拼成sql串,拿语句到sqlserver里执行。

可能方式有些笨拙,先这样啦,第一次用游标,感觉应该可以用一个游标的,但是试了半天没有试出来,就把单独的主键和联合主键分开了。

主键:au.constraint_type = 'P'

外键:au.constraint_type = 'F'



游标在pl/sql里执行看不到结果,需要用sql*plus

登录sql*plus conn 用户名/密码@orcl

设置显示结果 set serveroutput on;

然后执行如下两个游标,拷出结果,就是系统里所有的主键


单个的主键

declare

--类型定义

cursor CURSOR1 isselect a.column_name,b.* from user_cons_columns a ,

(select cu.TABLE_NAME,

au.constraint_type,

CU.CONSTRAINT_NAME ,--cu.column_name ,

cu.owner,

COUNT(cu.TABLE_NAME)

from user_cons_columns cu, user_constraints au

where cu.constraint_name = au.constraint_name

and au.constraint_type = 'P'

and cu.owner = 'GABSYSTEM'

-- and cu.table_name = 'SYSUSERDEPARTPOWER'

and cu.table_name notlike'BIN%'HAVINGCOUNT(CU.column_name) < 2

groupby cu.TABLE_NAME, au.constraint_type, CU.CONSTRAINT_NAME, cu.owner-- ,cu.column_name

ORDERBY CU.table_name) b

where a.table_name=b.table_name and a.owner = b.owner and a.constraint_name = b.constraint_name;

--定义一个游标变量

ccrec CURSOR1%rowtype;

begin

--for循环

OPEN CURSOR1;

LOOP

FETCH CURSOR1 INTO ccrec;

EXITWHEN CURSOR1%NOTFOUND;

dbms_output.put_line('ALTER TABLE '||ccrec.TABLE_NAME||' ADD CONSTRAINT '||ccrec.constraint_NAME ||' PRIMARY KEY ('||CCREC.column_name||');');

endloop;

CLOSE CURSOR1;

END;


复合主键的表

declare

--类型定义

cursor cursor1 isselect cu.TABLE_NAME, au.constraint_type, CU.CONSTRAINT_NAME,cu.owner,COUNT(cu.TABLE_NAME) from user_cons_columns cu, user_constraints au

where cu.constraint_name = au.constraint_name

and au.constraint_type = 'P'

and cu.owner = 'GABSYSTEM'

and cu.table_name notlike'BIN%'

HAVINGCOUNT(cu.TABLE_NAME) >2

groupby cu.TABLE_NAME,au.constraint_type,CU.CONSTRAINT_NAME,cu.owner

ORDERBY CU.table_name;


cursor cursor2 (tablename varchar2) is

select CU.CONSTRAINT_NAME,cu.COLUMN_NAME,cu.TABLE_NAME, au.constraint_type, cu.owner from user_cons_columns cu, user_constraints au

where cu.constraint_name = au.constraint_name

and au.constraint_type = 'P'

and cu.owner = 'GABSYSTEM'

and cu.table_name=tablename

ORDERBY CU.table_name;

--定义一个游标变量

ccrec cursor1%rowtype;

cctablename varchar2(200);

ddrec cursor2%rowtype;

allcolumn varchar2(1000);

begin

--for循环

OPEN cursor1;

LOOP

FETCH cursor1 INTO ccrec;

EXITWHEN cursor1%NOTFOUND;

-- dbms_output.put_line('cursor1--'||ccrec.TABLE_NAME||'-'||ccrec.constraint_type||'-'||ccrec.CONSTRAINT_NAME);

cctablename:=ccrec.TABLE_NAME;

allcolumn:=null;

OPEN cursor2(ccrec.TABLE_NAME);

LOOP

FETCH cursor2 INTO ddrec;

EXITWHEN cursor2%NOTFOUND;

--dbms_output.put_line('cursor2--'||ddrec.TABLE_NAME||'-'||ddrec.COLUMN_NAME||'-'||ddrec.constraint_type||'-'||ddrec.CONSTRAINT_NAME);

allcolumn:=allcolumn||','||ddrec.COLUMN_NAME;

ENDLOOP;

dbms_output.put_line('ALTER TABLE '||ddrec.TABLE_NAME||' ADD CONSTRAINT '|| ccrec.CONSTRAINT_NAME ||' PRIMARY KEY ('||substr(allcolumn,2,length(allcolumn)-1)||');');

CLOSE cursor2;

ENDLOOP;

CLOSE cursor1;

END;