在我正在处理的提取中,我有2个datetime列。一列存储日期,另一列存储如下所示的时间。

如何查询表,将这两个字段组合成类型为datetime的1列?

日期

2009-03-12 00:00:00.000
2009-03-26 00:00:00.000
2009-03-26 00:00:00.000

1899-12-30 12:30:00.000
1899-12-30 10:00:00.000
1899-12-30 10:00:00.000

当前回答

select s.SalesID from SalesTbl s 
        where cast(cast(s.SaleDate  as date) as datetime) + cast(cast(s.SaleCreatedDate as time) as datetime) between @FromDate and @ToDate

其他回答

DECLARE @Dates table ([Date] datetime);
DECLARE @Times table ([Time] datetime);

INSERT INTO @Dates VALUES('2009-03-12 00:00:00.000');
INSERT INTO @Dates VALUES('2009-03-26 00:00:00.000');
INSERT INTO @Dates VALUES('2009-03-30 00:00:00.000');

INSERT INTO @Times VALUES('1899-12-30 12:30:00.000');
INSERT INTO @Times VALUES('1899-12-30 10:00:00.000');
INSERT INTO @Times VALUES('1899-12-30 10:00:00.000');

WITH Dates (ID, [Date])
AS (
    SELECT ROW_NUMBER() OVER (ORDER BY [Date]), [Date] FROM @Dates
), Times (ID, [Time])
AS (
    SELECT ROW_NUMBER() OVER (ORDER BY [Time]), [Time] FROM @Times
)
SELECT Dates.[Date] + Times.[Time] FROM Dates
    JOIN Times ON Times.ID = Dates.ID

打印:

2009-03-12 10:00:00.000
2009-03-26 10:00:00.000
2009-03-30 12:30:00.000

如果你没有使用SQL Server 2008(即你只有一个DateTime数据类型),你可以使用以下(承认粗糙和准备就绪)TSQL来实现你想要的:

DECLARE @DateOnly AS datetime
DECLARE @TimeOnly AS datetime 

SET @DateOnly = '07 aug 2009 00:00:00'
SET @TimeOnly = '01 jan 1899 10:11:23'


-- Gives Date Only.
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @DateOnly))

-- Gives Time Only.
SELECT DATEADD(Day, -DATEDIFF(Day, 0, @TimeOnly), @TimeOnly)

-- Concatenates Date and Time parts.
SELECT
CAST(
    DATEADD(dd, 0, DATEDIFF(dd, 0, @DateOnly)) + ' ' +
    DATEADD(Day, -DATEDIFF(Day, 0, @TimeOnly), @TimeOnly)           
as datetime)

虽然粗糙,但很管用!

SELECT CAST(your_date_column AS date) + CAST(your_time_column AS datetime) FROM your_table

效果非常好

如果两个字段都是datetime,那么简单地添加它们就可以了。 例如: 声明@d datetime, @t datetime Set @d = '2009-03-12 00:00:00.000'; Set @t = ' 189-12-30 12:30:00.000'; 选择@d + @t 如果您使用Date & Time数据类型,则只需将时间转换为datetime 例如: 声明@d日期,@t时间 Set @d = '2009-03-12'; Set @t = '12:30:00.000'; 选择@d + cast(@t as datetime)

这是我的解决方案,它忽略了时间列的日期值

CAST(Tbl.date as DATETIME) + CAST(CAST(Tbl.TimeFrom AS TIME) as DATETIME)

希望这能帮助到其他人