sql—将时间变量放入smalldatetime变量的最简单方法(仅保留日期的时间部分)

kb5ga3dv  于 2021-07-24  发布在  Java
关注(0)|答案(5)|浏览(374)

我有两个变量

declare @dt1 smalldatetime = '2020-07-30 10:00:00'
declare @t1 time = '13:00:00'

最简单的方法是什么 t1dt1 得到 '2020-07-30 13:00:00' (不放松2020-07-30)

jyztefdp

jyztefdp1#

我会的 cast() 这个 smalldatetimedate 截断时间分量,然后返回 smalldatetime . 那你就可以 cast() 到其他时间分量到 smalldatetime 同时添加以下两项:

select 
    cast(cast(@dt1 as date) as smalldatetime) 
    + cast(@t1 as smalldatetime) as newdatetime

db小提琴演示:

| newdatetime      |
| :--------------- |
| 2020-07-30 13:00 |
yshpjwxd

yshpjwxd2#

SELECT REPLACE(REPLACE(REPLACE(@dt1,DATEPART(hour,@dt1),DATEPART(hour,@t1)),DATEPART(MINUTE,@dt1),DATEPART(MINUTE,@t1)),DATEPART(SECOND,@dt1),DATEPART(SECOND,@t1))
e5nszbig

e5nszbig3#

我个人会把它们转换成iso varchar 值、串联和转换回:

DECLARE @dt1 smalldatetime = '2020-07-30T10:00:00';
DECLARE @t1 time = '13:00:00';

SELECT CONVERT(smalldatetime,CONVERT(varchar(10),@dt1,126) + 'T' + CONVERT(varchar(8),@t1,114),126);
j5fpnvbx

j5fpnvbx4#

也许是这个?

declare @dt1 smalldatetime = '2020-07-30 10:00:00'
declare @t1 time = '13:00:00'

SELECT CAST(LEFT(CONCAT(CAST(@dt1 AS DATE), 'T', @t1), 19) AS SMALLDATETIME)
4smxwvx5

4smxwvx55#

你可以在电流的基础上再加三个小时 SMALLDATETIME 或者通过连接所需的部分来创建一个新的:

DECLARE @dt1 SMALLDATETIME = '2020-07-30 10:00:00'
DECLARE @t1 TIME = '13:00:00'

SELECT
    @dt1 AS "source",
    DATEADD(HOUR, 3, @dt1) AS "three hours added",  -- just add three hours
    CONVERT(SMALLDATETIME,  -- concatenate the desired parts and convert
        DATETIMEFROMPARTS(DATEPART(YEAR, @dt1),
                        DATEPART(MONTH, @dt1),
                        DATEPART(DAY, @dt1),
                        DATEPART(HOUR, @t1),
                        DATEPART(MINUTE, @t1),
                        DATEPART(SECOND, @t1),
                        0)
    ) AS "concatenated parts"

结果:

source              |three hours added      |concatenated parts
----------------------------------------------------------------
2020-07-30 10:00:00 |2020-07-30 13:00:00    |2020-07-30 13:00:00

相关问题