How to add dynamic column to an existing table

前端 未结 3 1753
抹茶落季
抹茶落季 2020-12-21 10:18

I have 2 tables 1st table contains following columns,

 id code    Name
 1  c1  chk1
 2  c2  chk2
 3  c3  chk3

2nd table contains following

相关标签:
3条回答
  • 2020-12-21 10:58

    Try this:

    CREATE PROCEDURE <procedurename>
    AS 
    BEGIN    
        DECLARE @COLUMN varchar(10), @SQL Varchar(100);
        SELECT @COLUMN = Name FROM Table1 
        WHERE id = (SELECT MAX(id) FROM Table1)
                    IF NOT EXISTS(
                                  SELECT COLUMN_NAME 
                                  FROM INFORMATION_SCHEMA.COLUMNS
                                  WHERE TABLE_NAME = 'Table2' 
                                  AND COLUMN_NAME = @COLUMN
                                 )
                     BEGIN
                       SELECT @SQL = 
                              'ALTER TABLE Table2 ADD '
                               +@COLUMN+' varchar(10),'
                               +@COLUMN+'_CompletedDate varchar(50)'
                       EXECUTE (@SQL)
                     END
    END
    
    0 讨论(0)
  • 2020-12-21 11:10

    Use Triggers as follows:

    CREATE TRIGGER AddDynamicColumn_to_table2
    ON Table1
    AFTER INSERT
    AS
    Exec ('ALTER TABLE Table2 ADD ' + (select name from inserted) + ' Varchar(10)')
    GO

    0 讨论(0)
  • 2020-12-21 11:14

    use this query as procedure.

    CREATE PROC ADD_CHECK
    AS 
    BEGIN
        DECLARE @COLUMN VARCHAR(50)
        DECLARE @QUERY VARCHAR(255)
        DECLARE @QUERY1 VARCHAR(255)
    
        SET @COLUMN= (SELECT TOP 1 NAME FROM TABLE1 WHERE ID=(SELECT MAX (ID)     FROM TABLE1))
    
        IF EXISTS(SELECT 1 FROM TABLE1 WHERE NAME=@COLUMN) 
        BEGIN
            SET @QUERY = 'ALTER TABLE TABLE2 ADD ' + @COLUMN + ' VARCHAR (50)'
            SET @QUERY1 = 'ALTER TABLE TABLE2 ADD ' + @COLUMN + '_COMPLETEDDATE VARCHAR     (50)'
            EXEC(@QUERY)
        END
    END
    
    0 讨论(0)
提交回复
热议问题