使用sql server 2000
Date Column数据类型为varchar
表1
ID Date
01 20100122
01 20100123
01 20100124
01 20100125
01 20100126
01 20090127
01 20090128
01 20090129
01 20090130
01 20090131
01 20090201
01 20100202
01 20090203
01 20100204
01 20100205
02
.....
从上表中,从1月26日到2月3日,这一年的所有内容都显示错误
我想更新年份而不是像2009年的20100127而不是20000127
预期输出
ID Date
01 20100126
01 20100127
...
01 20100203
...
02
像
一样查询update table1 set 2010 instead of 2009 where date between 20090126 and 20090203
如何查询更新值。
需要查询帮助
答案 0 :(得分:1)
如果列的类型为DATETIME,请查看DATEADD
SELECT GETDATE(), DATEADD(year, 1, GETDATE())
对于VARCHAR,您可以尝试类似
的内容DECLARE @Table TABLE(
Date VARCHAR(8)
)
INSERT INTO @Table SELECT '20090301'
SELECT *
FROM @Table
UPDATE @Table
SET Date = '2010' + RIGHT(Date, 4)
WHERE LEFT(Date,4) = '2009'
SELECT *
FROM @Table
或类似
DECLARE @Table TABLE(
ID VARCHAR(4),
Date VARCHAR(8)
)
INSERT INTO @Table SELECT '01','20100122'
INSERT INTO @Table SELECT '01','20100123'
INSERT INTO @Table SELECT '01','20100124'
INSERT INTO @Table SELECT '01','20100125'
INSERT INTO @Table SELECT '01','20100126'
INSERT INTO @Table SELECT '01','20090127'
INSERT INTO @Table SELECT '01','20090128'
INSERT INTO @Table SELECT '01','20090129'
INSERT INTO @Table SELECT '01','20090130'
INSERT INTO @Table SELECT '01','20090131'
INSERT INTO @Table SELECT '01','20090201'
INSERT INTO @Table SELECT '01','20100202'
INSERT INTO @Table SELECT '01','20090203'
INSERT INTO @Table SELECT '01','20100204'
INSERT INTO @Table SELECT '01','20100205'
UPDATE @Table
SET Date = '2010' + RIGHT(Date, 4)
WHERE Date >= '20090126'
AND Date <= '20090203'
AND ID = '01'
SELECT *
FROM @Table
答案 1 :(得分:1)
UPDATE Table1
SET Date = Replace(Date, '2009', '2010')
WHERE
DATE LIKE '2009%'
AND
convert(DATETIME, Date, 112) BETWEEN '2009-01-26 00:00:00' AND
'2009-02-03 23:59:59.999'
答案 2 :(得分:1)
更好的方法,避免更换9月20日
UPDATE Table1 Set Date = Replace(Date, '2009', '2010') WHERE DATE LIKE '2009%'
答案 3 :(得分:0)
如果列定义为varchar
:
update Table1
set [Date] = '2010' + substring([Date], 5, 4)
where [Date] between '20090126' and '20090203'
如果列定义为datetime
:
update Table1
set [Date] = convert(datetime, '2010-' + substring([Date], 5, 2) + '-' + substring([Date], 7, 2), 120)
where [Date] between {d'2009-01-26'} and {d'2009-02-03'}
注意:
{d'yyyy-mm-dd'}
语法不是合法的T-SQL,但它仍被任何SQL Server客户端堆栈正确拦截和解释,例如: ODBC,OLEDB,ADO.NET等。这也适用于交互式查询工具。如果您不喜欢使用ODBC转义序列,则可以使用convert(datetime, 'yyyy-mm-dd', 120)
代替。convert(datetime, 'yyyy-mm-dd', 120)
应用ODBC标准日期时间格式,它是culture / locale不变量,因此对于构造日期时间字符串非常有用,无论当前服务器区域设置如何。