Skip to main content

Add column to mid of table

In sql Server you cant add a column to mid of a table .If you add a new column to existing table then it will append end of the table. But in case of adding a column to to mid of the table you can do it like as follows;
  • Create a new table with the required columns,
  • Copy the data from the old table into the new table
  • Delete the old table
  • Then rename the new table.
Sample Code
---Old table
Create Table A
(col1 varchar(50) null,
col2 varchar(50) null)

--Add new column col3
Begin Transaction

Create Table B
(
col1 varchar(50) null,
col3 varchar(50) null, -- NEW COLUMN IN MIDDLE (NULLABLE)
col2 varchar(50) null
)
go
if exists(select * from A)
exec('insert into B (col1, col2)
select col1, col2 from A with (holdlock tablockx)')
go
drop table A
go
execute sp_rename 'B', 'A', 'object'
go

commit


Comments

Popular posts from this blog

Dead Code Problem

Problem Actually this problem occurred when i was doing integration two projects. [Phase1 and phase2 of a project] . Phase 2 is developed on top of the phase1. Parallel phase1 had changed lot . Mean time those were working on phase2 has commented existing phase 1 code without comments . Phase 1 and phase 2 merged with some conflicts. So we commented such places with the descriptive comment . After merged the result code base has merged those phase 2 commented parts. Also there was some of already dead code in phase 1. So it is difficult to understand weather this is actual dead code or commented one from phase 2. Mistake Had left dead dead code and missing comments . Lesson learned Normally developers leave dead code in their original code with the mind of future purpose. But this not a good habit to continue.As long as you use source control ,earlier code may exist. Problem will occur if you are not using such version control. In such a situation you can keep dead code with des...

Who's got the monkey ?

Today i found a interesting article on how manger should delegate his work. According to my understanding, this theory is highly applicable for software industry because most of the targets are accomplishing using teams.When we work in a team we should know what are the things need to be delegate.And those work must have to delegate.According to this theory problems are considered as monkeys. So everybody wants to know about how to deal with monkeys.