SQL server 2008 , add a column about the description of another column in a Table -


i need insert 1 column (varchar) 1 table table on sql server 2008.

table 1:

col1  col2  col3  bdh    6       28435 bdh    2       69 dwd    0       57 dwd    8       9742 

i need add column description of col1 in table 1.

e.g .

col1    id_desc          col2   col3  bdh                   6       28435 bdh                   2       69 dwd     excellent          0       57 dwd     excellent          8       9742 

table 2:

      col1  id_desc        bdh           dwd     excellent           

sql:

  insert  table 1   select  b.id_desc id_desc   table2 b    a.col1 = b.col1 

it not work.

the table has many records not efficient manually.

any appreciated.

here's short script shows how add new column existing table , fill in relevant data:

-- here i'm setting tables example data. create table [table 1] (col1 varchar(16), col2 int, col3 int); create table [table 2] (col1 varchar(16), id_desc varchar(16)); go  insert [table 1] values      ('bdh', 6, 28435),     ('bdh', 2, 69),     ('dwd', 0, 57),     ('dwd', 8, 9742); insert [table 2] values     ('bdh', 'good'),     ('dwd', 'excellent'); go  -- first, add column. must either nullable or have default value, -- since there extant records. alter table [table 1] add id_desc varchar(16) null; go  -- merge data [table 2] new column. update [table 1] set id_desc = t2.id_desc     [table 1] t1     inner join [table 2] t2 on t1.col1 = t2.col1; 

afterward, can alter column non-nullable if wish; i've made null because sql server needs have default value can insert new column existing rows.

there plenty of ways last part if don't update...from syntax; instance, can use merge or cte update.

finally, mentioned in comment above, might consider creating view:

create view table1vw select     t1.col1,     t2.id_desc,     t1.col2,     t1.col3     [table 1] t1     inner join [table 2] t2 on t1.col1 = t2.col1; 

you may have reason why you'd rather modify table instead, in absence of such reason, might alternative avoids redundant data storage , possible consistency issues later.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -