使用SQL Server 2005
Date Time
20060701 090000
20060702 020000
20060703 180000
...
日期和时间数据类型为varchar
尝试查询
select Convert(datetime, Convert(char(10), date, 103) + ' ' + Convert(char(8), time, 108), 103) from table
SELECT
CAST(
DATEADD(dd, 0, DATEDIFF(dd, 0, date)) + ' ' +
DATEADD(Day, -DATEDIFF(Day, 0, time), time)
as datetime) from table
它显示错误超出范围值。
如何解决这个问题。
需要Sql查询帮助
答案 0 :(得分:2)
首先,为什么要在VARCHAR中存储DATETIME?
这应该可以帮助
DECLARE @Table TABLE(
Val VARCHAR(20)
)
INSERT INTO @Table (Val) SELECT '20060701 090102'
INSERT INTO @Table (Val) SELECT '20060702 020000'
INSERT INTO @Table (Val) SELECT '20060703 180000'
SELECT *,
CAST(SUBSTRING(Val,1,8) + ' ' + SUBSTRING(Val,10,2) + ':' + SUBSTRING(Val,12,2) + ':' + SUBSTRING(Val,14,2) AS DATETIME)
FROM @Table
答案 1 :(得分:2)
CREATE FUNCTION fn_StringDateTietoDateTime
(
@Date varchar(15)
)
RETURNS datetime
AS
BEGIN
DECLARE @Result DATETIME
SET @Result = NULL
If len(@Date) > 0
BEGIN
SELECT @Result = CAST(SUBSTRING(@hl7date, 1, 8) + ' ' + SUBSTRING(@hl7date, 10, 2) + ':' +
SUBSTRING(@date, 12, 2) + ':' + SUBSTRING(@date,14, 2) AS DATETIME)
END
RETURN @RESULT
END