最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sql server - How to insert different values in a newly added column in a single update statement? - Stack Overflow

programmeradmin3浏览0评论

In t-SQL, I have added a new column named "AGE" to table "employees", but I have to write different update statements for insert each age value, since each employee has a different age.

Is there any way to insert different ages values into a single update statement? I cannot make use of default value or where condition, because there is no pattern in age of employees.

In t-SQL, I have added a new column named "AGE" to table "employees", but I have to write different update statements for insert each age value, since each employee has a different age.

Is there any way to insert different ages values into a single update statement? I cannot make use of default value or where condition, because there is no pattern in age of employees.

Share Improve this question asked Mar 17 at 9:15 Shivam Maurya 1729Shivam Maurya 1729 257 bronze badges 5
  • 7 "In t-SQL, I have added a new column named "AGE" to table "employees" FYI, people's ages change. Date of birth is a far better solution, as that doesn't change. – Thom A Commented Mar 17 at 9:16
  • Does this answer your question? SQL Update from One Table to Another Based on a ID Match – Thom A Commented Mar 17 at 9:17
  • 4 If you already have a DOB column then you can add a computed column with a formula to automatically derive the age at run time rather than storing it and needing to maintain it daily – Martin Smith Commented Mar 17 at 9:33
  • so how do you determine a person's age ? Do you have a column with the birtday or something else ? How do you know ? – GuidoG Commented Mar 17 at 12:02
  • Is it really a requirement that each employee has a different age? Please add DDL and sample data to clarify your question. – HABO Commented Mar 17 at 19:25
Add a comment  | 

1 Answer 1

Reset to default 2

Keeping a changing value in the database is not a great idea : each day someone may have his age change. The birthdate does not change.

For the technical side of the question :

  1. If you want to insert/update in "one" time, you have 2 options :
    Make several insert/update inside a transaction that you can rollback is case of error

  2. Construct a table then insert/update the content :

    UPDATE emp
    SET emp.Age = tmp.Age
    FROM dbo.Employee AS emp
    INNER JOIN (VALUES('name1', 25), ('name2', 52), ('name3', 34)) AS tmp(lastname, age)
          ON tmp.lastname = emp.lastname
    
发布评论

评论列表(0)

  1. 暂无评论