Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

sql - How to add dynamic column to an existing table

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 columns,

id,Name,Chk1,chk2,Chk3

i have to add the column 'Chk4' into table2 if table1 is updated with value '4,'c4','ch4' dynamically.How to write procedure to perform this?

i've tried the following procedure but its not working fine.

         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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...