SQL 在SQL中,如何在现有表中添加新列后添加值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31807768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In SQL, How to add values after add a new column in the existing table?
提问by Rampriya Rajendran
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?
我创建了一个表并插入了 3 行。然后我使用alter
. 如何在不使用任何空值的情况下向列添加值?
回答by GolezTrol
Two solutions.
两种解决方案。
- 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;
- Add the column with
null
values first. Then update all rows to enter the values you want.
- 首先添加带有
null
值的列。然后更新所有行以输入所需的值。
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
:
然后,如果需要,请更改列以使其成为not null
:
ALTER TABLE YourTable ALTER COLUMN YourNewColumn NOT NULL;
回答by Nikhil Kulkarni
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 :
假设您有一个 Employee 表,最初包含这些列 Employee_ID、Emp_Name、Emp_Email。稍后您决定将 Emp_Department 列添加到此表中。要为此列输入值,您可以使用以下查询:
Update *Table_Name* set *NewlyAddedColumnName*=Value where *Columname(primary key column)*=value
Example update TblEmployee set Emp_Department='Marketing' where Emp_ID='101'
例子 update TblEmployee set Emp_Department='Marketing' where Emp_ID='101'
回答by Venkatesh Panabaka
I think below SQL useful to you
我认为下面的 SQL 对你有用
update table_name set newly_added_column_name = value;
回答by Klaudiusz bryjamus
Why don't you use UPDATE statement:
为什么不使用 UPDATE 语句:
UPDATE tablename SET column=value <WHERE ...>
WHERE is optional. For instance in T-SQL for table:
WHERE 是可选的。例如在表的 T-SQL 中:
I can update column NewTestColumn by this statement:
我可以通过此语句更新列 NewTestColumn:
UPDATE [dbo].[Table] SET [NewTestColumn] = 'Some value'
回答by david sam
update table_name
set new_column=value
回答by sachin yadav
suppose emp is the table and Comm is the new column then fire the below query .
假设 emp 是表,Comm 是新列,然后触发以下查询。
update emp set Comm=5000
回答by Vrushabh
Update table table_name set column_name = value where 'condition';
I preferred to use p.key
column for best result.
我更喜欢使用p.key
列以获得最佳结果。