0

我在一个视图中有两列给我日期部分。

它们是月份和年份。

我需要一个新列,它是一个日期/时间字段。它必须是其他两列提供的月份和年份的第一天。

4, 2011需要

2011-04-01 00:00:00.000

在新列中

当前设置如下所示:

month_number    incident_year
4   2011
5   2011
6   2011
7   2011
8   2011
9   2011
10  2011
11  2011
12  2011
1   2012
2   2012
3   2012
4   2012
5   2012
6   2012
4

3 回答 3

3
SELECT 
  incident_year, month_number,
  dt = DATEADD(MONTH, (incident_year-1900)*12+month_number-1, '19000101') 
  FROM dbo.view_name;

您还可以使用 0-date 使其更简洁:

SELECT 
  incident_year, month_number,
  dt = DATEADD(MONTH, (incident_year-1900)*12+month_number-1, 0) 
  FROM dbo.view_name;

在 SQL Server 2012 中,您将能够更简单地执行此操作:

SELECT DATEFROMPARTS(incident_year, month_number, 1)
  FROM dbo.view_name;
于 2012-07-12T15:43:08.343 回答
1
 Select CAST(CAST( incident_year AS varchar(4)) + '-' + 
        CAST(month_number AS varchar(2)) + '-01' AS DATETIME) as incident_Year
 from YourView
于 2012-07-12T15:39:23.360 回答
0
Alter table yourTable add newDateColumn datetime NULL

update yourTable set newDateColumn = 
   CONVERT(datetime, CAST(incident_year as varchar(4)) +'-' CAST(month_number as varchar(2))+'-01 00:00:00.000', varchar(30)) 
   from YourTable
于 2012-07-12T15:42:37.133 回答