SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Alter & Update in IF condition
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Ken Blum
Constraint Violating Yak Guru

383 Posts

Posted - 07/30/2013 :  11:19:10  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3585 Posts

Posted - 07/30/2013 :  12:47:08  Show Profile  Reply with Quote
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 - 07/30/2013 :  13:39:27  Show Profile  Reply with Quote
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

India
52317 Posts

Posted - 07/31/2013 :  02:41:26  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000