views:

46

answers:

2

if I have a stored procedure say

CREATE PROCURE w AS

ALTER TABLE t ADD x char(1)

UPDATE t set x =1

Even when it lets me create that stored procedure (if I create it when x exists), when it runs, there is an error on the UPDATE statement because column x doesn't exist.

What's the conventional way to deal with this, it must come up all the time? I can work around it by putting the UPDATE inside EXEC, is there another/better way?

Thanks

+2  A: 

Rather than adding a column like this and then updating its value, you can add a column with a default value

CREATE PROCEDURE w AS 

ALTER TABLE t ADD x char(1) NOT NULL CONSTRAINT abc DEFAULT 1
Pranay Rana
Elegant solution! But will work, I guess, only if new column doesn't allow NULL
abatishchev
Thanks, but 1 isn't actually the value i want in there, I want to update the new column to a value from a "FROM" clause; I just had 1 in my example as a placeholder to show something simple that caused the error.
TortTupper
than first get the value in varible and than use here select @@variable=1 ALTER TABLE t ADD x char(1) NOT NULL CONSTRAINT abc DEFAULT @@variable may work for you
Pranay Rana
+2  A: 

ALTER TABLE in the context of 1st TRANSACTION and UPDATE in the context of 2nd:

CREATE PROCEDURE w
AS
   BEGIN TRAN
      ALTER TABLE ..
   COMMIT

   BEGIN TRAN
      UPDATE ..
   COMMIT
END
abatishchev
Sounds attactive but I can't make it work: CREATE PROCEDURE p AS BEGIN TRAN ALTER TABLE t ADD x CHAR (1) COMMIT BEGIN TRAN UPDATE t SET x = 1 COMMIT If I use "END" I get a syntax errror. If I successfully create it the procedure, I still get the same errror if "x" doesn't exist at run time (and would get another error if it did exist)
TortTupper
@TortTupper: It seems that's a limitation of SQL Server. How about file a bug on MS.Connect? I would upvote it. My workaround: create 2 separate SPs and call them turn-by-turn. Or create a 3rd which will call 1st and 2nd
abatishchev
@TortTupper: Another idea why does it happen. SQL Server can't create a SP accessing a not-yet-existed column during SP creation. So maybe your task is impossible yet.. (
abatishchev
Well, for me it worked to put the update statements into Exec('WITH blahblhablah....'), but I did have single quotes already in my update statement, so that came up ugly, and my point is to try to make the process self-explanatory, so I may well break it into two separate sps. Thanks.
TortTupper