Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Alter & Update in IF condition

Author  Topic 

Ken Blum
Constraint Violating Yak Guru

383 Posts

Posted - 2013-07-30 : 11:19:10
How come the update fails? The ALTER statements are only effective after the GO. If I move the UPDATE outside the BEGIN/END then all works ok. What do I need to do to commit the ALTER before the UPDATE - I also tried BEGIN/COMMIT Transaction

IF NOT EXISTS(select * from sys.columns where Name = N'xNewCol' and Object_ID = Object_ID(N'myTable'))    
BEGIN
ALTER TABLE myTable ALTER COLUMN xOldCol float NULL
ALTER TABLE myTable ADD xNewCol float NULL

UPDATE myTable
SET xNewCol = ROUND(xCol1/xOldCol, 2)
WHERE xOldCol != 0
END
GO

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-07-30 : 12:47:08
This is the expected behavior. I am not sure that it will work even if you move the update statement outside of the Begin/END block and if xNewCol did not exist.

When you send a query to SQL Server, each segment of code between the batch separators (GO) is considered a single batch and evaluated as a single unit based on the schema that exists at the time the evaluation happens. SQL Server does not evaluate the schema changes within that batch for this purpose.
Go to Top of Page

Ken Blum
Constraint Violating Yak Guru

383 Posts

Posted - 2013-07-30 : 13:39:27
OK thanks. Guess I will set a local variable to determine whether I need to perform update or not.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-07-31 : 02:41:26
quote:
Originally posted by Ken Blum

OK thanks. Guess I will set a local variable to determine whether I need to perform update or not.


Even then the DDL has to be in a prior batch for you to use the newly created column in update

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -