I have 2 tables, A and B. Table A has columns Q1, Q2, Q3, Q4 and Table B has columns Q1 and Q2 along with others. In Table A, columns will get changed in future with Q5, Q6, Q7 etc. I want to write dynamic SQL to alter the table B (adding new columns) whenever new columns are added to Table A. Columns which will get added always be like Q1, Q2,Q3...Q40.
example of my tables:
create table tableA
(
[sid] [varchar](50) not null,
[rid] [varchar](50) not null,
[Q_URL] [varchar](500) null,
[Q1] int null,
[Q2] int null,
[Q3] int null,
[Q4] int null
);
create table tableB
(
[s_id] [varchar](50) not null,
[rid] [varchar](50) not null,
[Q_URL] [varchar](500) null,
[Q1] int null,
[Q2] int null
);
information_schema.columnsfor this to build out your dynamic SQL but it will be terribly brittle and you will probably have to trigger it with DDL triggers which will get messy. It sounds like you want a database versioning solution rather than just some dynamic SQL.sid varchar(50), rid varchar(50), Q_URL varchar(500), Q_NUMBER int, value int. This way you don't need to keep adding columns, instead you have one row per sid, rid, Q_NUMBER combination.