Friday, February 24, 2012

Can Add/update/drop column sql statements in one store procedure?

I have a batch sql statments to add column NewCol into TableA, then update
NewCol at this TableA, then drop column NewCol from TableA. I have no proble
m
to run them as individual sql statment with GO after each statment. But when
I tried to put these sql statements into one store procedure, each time when
compile or run the store procedure, I got error 'Invalid column name'. I
guess column NewCol is not there at beginning. So Can I put Add/update/drop
column in one store procedure?
alter procedure xash
AS
-- other sql regarding to this TableA --
--alter add column--
alter table TableA add NewCol varchar(1) null
-- update new column--
Update TableA
set NewCol= 'Y'
--other operation related this table and new column--
--drop column --
alter table TableA drop COLUMN NewCol
GOYou have to commit the work at each step before the next step can see
it. There is lots of overhead for this.
I have to ask why you are doing this. Instead of having physical
storage hold your computed values, wouldn't it be better to simply have
a VIEW with the computed column in it? Also why do you want to use
VARCHAR(1); think about it.
CREATE VIEW FilteredFoobar (..)
AS
SELECT ..., CASE WHEN <<test here>> THEN 'Y' ELSE 'N' END AS new-col
FROM Foobar, ..
WHERE ..;|||On 13 Apr 2005 16:18:15 -0700, --CELKO-- wrote:

> Also why do you want to use VARCHAR(1); think about it.
You know, it would be nice if SQL implementations could just throw an error
message if you try to create a VARCHAR(1) column. :)

No comments:

Post a Comment