sql动态添加字段

来源:互联网 发布:大数据教材 编辑:程序博客网 时间:2024/05/16 23:41

--先将需要添加的字段保存到一张表(xxx)中

create table xxx

(

c_name nvarchar(50),

c_type nvarchar(50)

)

 

delete xxx

 

insert into xxx values('colum1', 'nvarchar(50)')

insert into xxx values('colum2', 'nvarchar(50)')

 

--创建需要动态添加字段的表(aaa)

create table aaa(id int)--做示例只指定了一个字段

 

--然后用游标循环xxx中的内容拼接alter语句并执行

declare my_cursor cursor scroll dynamic

for

select c_name,c_type from  xxx

open my_cursor

declare @c_name nvarchar(1000), @c_type nvarchar(1000), @strSql nvarchar(1000)

set @strSql='alter table aaa add '

fetch next from my_cursor into @c_name, @c_type

while(@@fetch_status=0)

  begin

set @strSql = @strSql + ' ' + @c_name + ' ' + @c_type + ','

    fetch next from my_cursor into @c_name, @c_type

  end

fetch first from my_cursor into @c_name, @c_type

set @strSql = substring(@strSql, 0, len(@strSql))

exec sp_executesql @strSql

close my_cursor

deallocate my_cursor

 

至此就可以了

原创粉丝点击