Adding columns dynamicly by query in MS SQL Server -


i have 2 tables in sql server 2012.

tablea

enter image description here

now want add tablea's (name) rows @ tableb varchar(150) column. result below:

tableb

enter image description here

how can this?

you can add columns dynamically using below code, building dynamic alter table statement add multiple columns @ once.

 create table tablea (name varchar(10), nametype varchar(20))     insert tablea values ('a','excellent'),('b','good'),('c','poor')      create table tableb(id int, fullname varchar(20), gender char(2))  -- check table column     select * tableb       declare @cols nvarchar(max),         @query  nvarchar(max)      select @cols = stuff((select  ',' + quotename(name)  +' varchar(150)'                          tablea                         order name                 xml path(''), type                 ).value('.', 'nvarchar(max)')              ,1,1,'')      set @query = 'alter table dbo.tableb add ' + @cols       exec (@query)  -- check table column     select * tableb 

Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -