CREATE FUNCTION [DBO].[to_date](@P_FORMAT VARCHAR(30),
@P_STRING VARCHAR(30))
RETURNS DATETIME
AS
BEGIN
DECLARE @V_DAY INT
DECLARE @V_MONTH INT
DECLARE @V_YEAR INT
DECLARE @V_HOUR INT
DECLARE @V_MINUTE INT
DECLARE @V_SECOND INT
DECLARE @V_DATETIME DATETIME
SET @V_DAY = charindex('dd', @P_FORMAT)
SET @V_MONTH = charindex('mm', @P_FORMAT)
SET @V_YEAR = charindex('yyyy', @P_FORMAT)
SET @V_HOUR = charindex('hh', @P_FORMAT);
SET @V_MINUTE = charindex('nn', @P_FORMAT);
SET @V_SECOND = charindex('ss', @P_FORMAT);
IF @V_DAY = 0
SET @V_DAY=1
ELSE
SET @V_DAY=CONVERT(INT, substring(@P_STRING, @V_DAY, 2));
IF @V_MONTH = 0
SET @V_MONTH=1
ELSE
SET @V_MONTH=CONVERT(INT, substring(@P_STRING, @V_MONTH, 2));
IF @V_YEAR = 0
SET @V_YEAR=2000
ELSE
SET @V_YEAR=CONVERT(INT, substring(@P_STRING, @V_YEAR, 4));
IF @V_HOUR = 0
SET @V_HOUR=0
ELSE
SET @V_HOUR=CONVERT(INT, substring(@P_STRING, @V_HOUR, 2));
IF @V_MINUTE = 0
SET @V_MINUTE=0
ELSE
SET @V_MINUTE=CONVERT(INT, substring(@P_STRING, @V_MINUTE, 2));
IF @V_SECOND = 0
SET @V_SECOND=0
ELSE
SET @V_SECOND=CONVERT(INT, substring(@P_STRING, @V_SECOND, 2));
SET @V_DATETIME=CONVERT(DATETIME, cast(@V_YEAR AS VARCHAR) + '-'
+ cast(@V_MONTH AS VARCHAR) + '-'
+ cast(@V_DAY AS VARCHAR) + ' '
+ cast(@V_HOUR AS VARCHAR) + ':'
+ cast(@V_MINUTE AS VARCHAR) + ':'
+ cast(@V_SECOND AS VARCHAR), 120);
RETURN @V_DATETIME;
END
那是節省了我的時間堆,Muchus格拉西亞斯 – Chin 2010-04-03 02:35:37
@Chin當心你的優勢的情況下爲上面的代碼不會與它「2003-12-31 10點07分42秒」返回的記錄。沒有時間,它被假定爲0:00:00。你可能想使用'01/01/2004'或'12/31/2003 23:59:59' – SqlACID 2010-04-03 02:49:12
使用明確的格式'CONVERT(datetime,'01/01/2003',103)''會爲你節省一個很多潛在的問題。 – erikkallen 2010-04-03 09:26:02