Use triggers to dynamically add columns

Source: Internet
Author: User

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
Test:
Insert Ta
Select 10 Union all
Select 13 Union all
Select 18 Union all
Select 26
Query:
Select * from TB

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

(The number of affected rows is 1)

-- Drop table Ta, TB
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.