开发者

Add a column into table after the table is created

I have already created a table named starsin. Now I want to add a column address in my table starsin by usin开发者_开发百科g a query. How can I do this?


In standard SQL, you want the alter table X add column Y ... command.

If you then want to populate the column for all existing rows, it's a simple matter of working out the query and: update X set Y = ....


Here's an example session which shows you the alter table add column in action (for DB2):

> CREATE TABLE XYZ (F1 INTEGER);                       
DSNE616I STATEMENT EXECUTION WAS SUCCESSFUL, SQLCODE IS 0  

> INSERT INTO XYZ VALUES (1);                          
DSNE615I NUMBER OF ROWS AFFECTED IS 1                      
DSNE616I STATEMENT EXECUTION WAS SUCCESSFUL, SQLCODE IS 0  

> INSERT INTO XYZ VALUES (2);                          
DSNE615I NUMBER OF ROWS AFFECTED IS 1                      
DSNE616I STATEMENT EXECUTION WAS SUCCESSFUL, SQLCODE IS 0  

> SELECT * FROM XYZ;                                   
F1                                                
--
 1                                                
 2                                                
DSNE610I NUMBER OF ROWS DISPLAYED IS 2                     
DSNE616I STATEMENT EXECUTION WAS SUCCESSFUL, SQLCODE IS 100

> ALTER TABLE XYZ ADD COLUMN F2 INTEGER;               
DSNE616I STATEMENT EXECUTION WAS SUCCESSFUL, SQLCODE IS 0  

> UPDATE XYZ SET F2 = F1 + 7;                          
DSNE615I NUMBER OF ROWS AFFECTED IS 2                      
DSNE616I STATEMENT EXECUTION WAS SUCCESSFUL, SQLCODE IS 0  

> SELECT * FROM XYZ;                                   
F1   F2                                   
--   --
 1    8                                   
 2    9                                   
DSNE610I NUMBER OF ROWS DISPLAYED IS 2                     
DSNE616I STATEMENT EXECUTION WAS SUCCESSFUL, SQLCODE IS 100


If this is mysql, you can do ALTER TABLE stasin ADD COLUMN <columnname> <type> <options>


See here

Code:

ALTER TABLE Sales 
ADD UnitPrice MONEY;

Output: The command(s) completed successfully. Explanation: This example adds a single field to the 'Sales' table by specifying the new field name and data type. Language(s): MS SQL Server


ALTER TABLE <table name> ADD(<coloumn name> <datatype>);

Normal SQL query to add a coloumn. In oracle, it will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜