如何将动态列添加到现有表

时间:2014-04-29 06:16:32

标签: sql sql-server sql-server-2008 sql-server-2008-r2 sql-server-2012

我有2个表第1个表包含以下列,

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

第二个表包含以下列,

id,Name,Chk1,chk2,Chk3

我必须添加专栏' Chk4'如果table1更新为值' 4,' c4',' ch4'动态。如何编写程序来执行此操作?

我已尝试过以下程序,但效果不佳。

         create proc Add_Check
          as 
          begin
          declare @Column varchar(50)
          declare @query varchar(255)
          declare @query1 varchar(255)
          set @Column= (select top 1 QUOTENAME(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

3 个答案:

答案 0 :(得分:1)

将此查询用作过程。

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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:-1)

使用触发器如下:

创建触发器AddDynamicColumn_to_table2
见表1 插入后 AS
Exec(&#39; ALTER TABLE Table2 ADD&#39; +(从插入中选择名称)+&#39; Varchar(10)&#39;)
GO