SQL Server - Invalid Column Name ‘ABC’ Error While Accessing Newly Added Column

In this blog, we will look into accessing a newly-added column to a table. We can add a new column to an existing table.
  1. using ALTER statement using:  
  2. ALTER TABLE table_name  
  3. ADD column_name datatype;  
Similarly, we can drop a column using following code.
  1. ALTER TABLE table_name  
  2. DROP COLUMN column_name;   
We can change the data type of an existing column.
  1. ALTER TABLE table_name  
  2. ALTER COLUMN column_name datatype; 
When we add a new column using ALTER TABLE statement, then try to access immediately in the same batch using SELECT\UPDATE\INSERT statement. It will throw the below error:
 
 
This error is because the newly added column will be reflected only after completion of the current batch. To fix it, we can split it into two different batches separated by batch separator [GO].
 
 

We can also use dynamic SQL instead of splitting into two batches as shown below.
 

 I attached SQL script and am ending here. I hope this is informative.
Ebook Download
View all
Learn
View all