Welcome to 2PTTechnology Sign in | Join
in Search

Create or Add columns to a table dynamically

Last post 03-10-2008, 5:04 PM by twaligora. 0 replies.
Sort Posts: Previous Next
  •  03-10-2008, 5:04 PM 139

    Create or Add columns to a table dynamically

    if exists (select * from sysobjects where id = object_id(N'[dbo].[table_name_Here]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

    drop table [dbo].[table_name_Here]

    GO

    Create table table_name_Here (ID int) --Name the table here and we will create one static field

    select * from table_name_Here -- here is the table before

     

    Declare @SQL varchar(1000)

    Declare @Counter int

    set @Counter = 1

    while @Counter <= 5 -- Change this number to add Columns

    begin

    set @SQL = 'ALTER TABLE table_name_Here

    ADD ColName' + rtrim(convert(char(10),@Counter)) + ' numeric(18,0)'

    exec(@SQL)

    set @Counter = @Counter + 1

    end

    select * from table_name_Here --here is the table after

View as RSS news feed in XML
Powered by Community Server, by Telligent Systems