SQL Server:使用DATEPART设置日期

时间:2016-01-20 11:22:44

标签: sql sql-server tsql

我有一个表,其中一些行的日期年份设置为1990.我想将所有这些行设置为2016.例如,1990-01-06将成为2016-01-06。

这就是我现在所拥有的

UPDATE [tableName]
SET recievedDate = new DateTime() 
     //where I want to make a new datetime with 2016 as the year
WHERE DATEPART(yyyy, receivedDate) = '1990' 
  AND DATEPART(mm, receivedDate) = '01';

3 个答案:

答案 0 :(得分:3)

您可以使用DATEADD26年添加到1990

CREATE TABLE #tableName(receivedDate DATE);
INSERT INTO #tableName(receivedDate) VALUES ('1990-01-06'),('1990-01-16');

UPDATE #tableName
SET receivedDate = DATEADD(YEAR, 26, receivedDate)
WHERE DATEPART(yyyy, receivedDate) = '1990' 
  AND DATEPART(mm, receivedDate) = '01';

SELECT *
FROM #tableName;

LiveDemo

SQL Server 2012 + 您可以使用DATEFROMPARTS

UPDATE #tableName
SET receivedDate = DATEFROMPARTS(2016,
                                 DATEPART(mm, receivedDate),
                                 DATEPART(dd, receivedDate)
                                )
WHERE DATEPART(yyyy, receivedDate) = '1990' 
  AND DATEPART(mm, receivedDate) = '01';

LiveDemo2

修改

保持表达式DATEPART(yyyy, receivedDate) = '1990'不是SARGable,查询优化器将跳过索引ob receivedDate(如果存在的话)。您可以使用BETWEEN>= <之类的Gordon Linoff

答案 1 :(得分:1)

由于CONVERT(varchar, yourdate, 126)以一种格式返回一个字符串&#34; 2016-01-04T07:45:00&#34;可以使用以下声明:

update YourTable set 
    yourdate = CAST('2016' + substring(CONVERT(varchar, yourdate, 126), 5, 15) as datetime)
where YEAR(yourdate) = 1990 AND MONTH(yordate) = 1

答案 2 :(得分:1)

正如lad2025解释的那样,正确的解决方案是增加26年。但是,查询本身更好地编写如下:

UPDATE tableName
    SET receivedDate = DATEADD(YEAR, 26, receivedDate)
    WHERE receivedDate >= '1990-01-01' AND
          receivedDate < '1990-02-01';

此版本允许查询利用包含receivedDate作为第一列的任何索引,这可以显着提高性能。