Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

sql - alter table then update in single statement

I have a requirement where I need to Alter (Add 2 columns) and then update the same table.

Here is the query I tried:

ALTER TABLE A
ADD c1 int,c2 varchar(10)

UPDATE  A set c1 = 23, c2 = 'ZZXX'

I need to run the above two queries at a time.

I am using Talend ETL tool, in this we have a component tMssqlrow, which allow us to run multiple queries (I am using 10 to 15 update queries in single component).

But the above query is not working.

I tested in DataBase Microsoft SQL. i am getting the below error :

Msg 207, Level 16, State 1, Line 5

Invalid column name 'c1'. Msg 207,

Level 16, State 1, Line 5

Invalid column name 'c2'.

can any one help me resolve this problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't do this exactly in a single statement (or batch) and it seems the tool you are using does not support GO as a batch delimiter.

You can use EXEC to run it in a child batch though.

ALTER TABLE A
  ADD c1 INT, c2 VARCHAR(10);

EXEC('
UPDATE A
SET    c1 = 23,
       c2 = ''ZZXX'';
    ');

NB: All single quotes in the query need to be doubled up as above to escape them inside a string literal.

Or alternatively you could achieve similar results in a single statement with the aid of some default constraints.

ALTER TABLE A
  ADD c1 INT NULL CONSTRAINT DF_A_c1 DEFAULT 23 WITH VALUES, 
     c2 VARCHAR(10) CONSTRAINT DF_A_c2 NULL DEFAULT 'ZZXX' WITH VALUES;

But this is not exactly the same as the original query as the default constraints will be left behind and may need to be dropped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...