如何动态描述表名
表_dmbnote中的dmbname字段中存放了50多个代码表的表名,我想用如下的存储过程来建这些表的主键,(所有代码表的要建主键得列名都为code)
CREATE PROCEDURE usp_create_pk
AS
declare @bm varchar(7)
declare cur_dmb cursor for select dmbname from _dmbnote
open cur_dmb
fetch cur_dmb into @bm
if (@@fetch_status<>0)
begin
close cyr_dmb
deallocate cur_dmb
return
end
set nocount on
while (@@fetch_status=0)
begin
alter table XXX add constraint pk_code primary key (code)
////////XXX应为@BM的内容,在此如何写(象VF中的宏代换‘&’)
fetch next into @bm
end
close cur_dmb
deallocate cur_dmb
return
问题点数:50、回复次数:3Top
1 楼westbulls(westbulls)回复于 2003-10-04 16:36:33 得分 10
只写其中一段
declare @sql varchar(8000)
while (@@fetch_status=0)
begin
select @sql='alter table ['+@bm+'] add constraint pk_code primary key (code)
exec(@sql)
fetch next into @bm
endTop
2 楼pengdali()回复于 2003-10-04 16:36:36 得分 10
CREATE PROCEDURE usp_create_pk
AS
declare @bm varchar(7)
declare cur_dmb cursor for select dmbname from _dmbnote
open cur_dmb
fetch cur_dmb into @bm
if (@@fetch_status<>0)
begin
close cyr_dmb
deallocate cur_dmb
return
end
set nocount on
while (@@fetch_status=0)
begin
exec('alter table '+@bm+' add constraint pk_code primary key (code)')
fetch next into @bm
end
close cur_dmb
deallocate cur_dmb
return
Top
3 楼txlicenhe(马可)回复于 2003-10-04 16:42:48 得分 30
CREATE PROCEDURE usp_create_pk
AS
declare @bm varchar(7)
declare cur_dmb cursor for select dmbname from _dmbnote
open cur_dmb
fetch cur_dmb into @bm
if (@@fetch_status<>0)
begin
close cyr_dmb
deallocate cur_dmb
return
end
set nocount on
while (@@fetch_status=0)
begin
exec('alter table '+@bm+' add constraint pk_code_'+@bm+' primary key (code)')
--(主键名也不能与其它表的主键名重复)
-- alter table XXX add constraint pk_code primary key (code)
fetch next into @bm
end
close cur_dmb
deallocate cur_dmb
return
Top




