[英]The UPDATE statement in SQL
I am working on TableA that has Column1 with dates in this format: YYYY-MM-DD and Column2 with numbers range from 1-12.我正在处理 TableA,它的 Column1 的日期格式为:YYYY-MM-DD 和 Column2,数字范围为 1-12。 I am trying to change the date year (THE YEAR ONLY) to 2022 WHERE Column2 = 10
我正在尝试将日期年份(仅年份)更改为 2022 WHERE Column2 = 10
NOTE: I am not trying to change the months and date.注意:我不是要更改月份和日期。 Data type is date.
数据类型是日期。
UPDATE TableA
SET Column1 = '2021'
WHERE Column2 = 10
Ideally you would never store a date as a string - use the correct datatype ie date
.理想情况下,您永远不会将日期存储为字符串——使用正确的数据类型,即
date
。 Also I assume YYY-MM-DD
is a typo and that it should read YYYY-MM-DD
.我还假设
YYY-MM-DD
是一个错字,它应该读作YYYY-MM-DD
。
Then a simple string concatenation should work然后一个简单的字符串连接应该工作
create table TestTable (Column1 varchar(10), Column2 int);
insert into TestTable (Column1, Column2)
select '2021-12-10', 10;
update TestTable set
Column1 = CONCAT('2022', SUBSTRING(Column1,5,6))
where Column2 = 10;
select * from TestTable;
Returns:退货:
Column1![]() |
Column2![]() |
---|---|
2022-12-10 ![]() |
10 ![]() |
Note: Works on both SQL Server and MySQL.注意:适用于 SQL 服务器和 MySQL。
If you are storing your dates as date data type , then you could do it mathematically as the following:如果您将日期存储为日期数据类型,那么您可以按照以下数学方式进行操作:
For SQL server:对于 SQL 服务器:
update TableA
set Column1 = dateadd(year, -(year(Column1) - 2022), Column1)
where Column2 = 10
For MySQL对于 MySQL
update TableA
set Column1 = date_add(Column1, interval -(year(Column1) - 2022) year)
where Column2 = 10
UPDATE TableA
SET Column1 = '2022' + substring(Column1,6,5)
WHERE Column2 = 10
So it is hard replacing 2022 to the first 4 characters and appending the rest of column1 to the end所以很难将 2022 替换为前 4 个字符并将 column1 的 rest 附加到末尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.