用触发器实现动态新增列

create table ta(number int)

create trigger test_tr on ta
for insert
as
begin
DECLARE @number int,@sql varchar(4000),@sql1 varchar(4000),@i int
DECLARE roy CURSOR
FOR SELECT * from inserted
OPEN roy
FETCH next FROM roy into @number
WHILE @@FETCH_STATUS = 0
begin
begin
  if exists(select 1 from sysobjects where name='tb' and xtype='U')
    begin
         select @i=max(colid)+1 from syscolumns where id=object_id('tb')
         set @sql=N'alter table tb add C'+cast(@i as varchar)+' int null'
         set @sql1=N'update tb set C'+cast(@i as varchar)+'='+cast(@number as varchar)
--print @sql
--print @sql1
         exec(@sql)
         exec(@sql1)
    end
else
    begin
         set @sql=N'create table tb(C1 int)'
         set @sql1=N' insert tb select C1='+cast(@number as varchar)
         exec(@sql)
         exec(@sql1)
    end
end
FETCH NEXT FROM roy INTO @number
end
CLOSE roy
DEALLOCATE roy
end
测试:
insert ta
select 10 union all
select 13 union all
select 18 union all
select 26
查询:
select * from tb

C1          C2          C3          C4         
----------- ----------- ----------- -----------
10          13          18          26

(所影响的行数为 1 行)

--drop table ta,tb
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值