In SQL, How to add values after add a new column in the existing table?

前端 未结 7 1468
臣服心动
臣服心动 2021-02-14 13:34

I created a table and inserted 3 rows. Then I added a new column using alter. How can I add values to the column without using any null values?

相关标签:
7条回答
  • 2021-02-14 13:45
    Update table table_name set column_name = value where 'condition'; 
    

    I preferred to use p.key column for best result.

    0 讨论(0)
  • 2021-02-14 13:48

    Two solutions.

    1. Provide a default value for the column. This value will be used initially for all existing rows. The exact syntax depends on your database, but will will usually look like ..

    this:

    ALTER TABLE YourTable
    ADD YourNewColumn INT NOT NULL
    DEFAULT 10 
    WITH VALUES;
    
    1. Add the column with null values first. Then update all rows to enter the values you want.

    Like so:

    ALTER TABLE YourTable
    ADD YourNewColumn INT NULL;
    
    UPDATE YourTable SET YourNewColumn = 10; -- Or some more complex expression
    

    Then, if you need to, alter the column to make it not null:

    ALTER TABLE YourTable ALTER COLUMN YourNewColumn NOT NULL;
    
    0 讨论(0)
  • 2021-02-14 13:49

    Suppose you have a Employee table with these columns Employee_ID, Emp_Name,Emp_Email initially. Later you decide to add Emp_Department column to this table. To enter values to this column, you can use the following query :

    Update *Table_Name* set *NewlyAddedColumnName*=Value where *Columname(primary key column)*=value
    

    Example update TblEmployee set Emp_Department='Marketing' where Emp_ID='101'

    0 讨论(0)
  • 2021-02-14 13:49

    suppose emp is the table and Comm is the new column then fire the below query .

    update emp set Comm=5000 
    
    0 讨论(0)
  • 2021-02-14 14:00
       update table_name
       set new_column=value
    
    0 讨论(0)
  • 2021-02-14 14:03

    I think below SQL useful to you

    update table_name set newly_added_column_name = value;
    
    0 讨论(0)
提交回复
热议问题