我需要选择并插入table1 database1中的信息并将其插入table1 database2。问题是这些记录有一个varchar日期(2012年12月12日)我想将该日期转换为datetime,然后将其插入到database2的另一个表中。我怎么能这样做?
我正在使用此代码进行测试:
DECLARE @date nvarchar(30)
SET @date = '12 of enero of 2012'
PRINT @date
PRINT cast((REPLACE('12 of enero of 2012', 'of', '')as datetime)
答案 0 :(得分:1)
你可以简单地投射它,就像这样
SELECT CAST(REPLACE('12 of december of 2011', 'of ', '') AS DATETIME)
所以你需要做的就是插入
-- In your last update I noticed you are using Spanish
-- So you'll have to put <b>SET LANGUAGE SPANISH</b> before your query
INSERT INTO TABLE1 (MyDateTimeField)
SELECT CAST(REPLACE(MyVarCharThatContainsDateTimeField, 'of ', '') AS DATETIME)
FROM TABLE2
请注意,如果您的字符串不是日期,则会抛出错误:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
答案 1 :(得分:0)
CONVERT函数用于转换此日期格式。
convert(datetime, '12 december 2012')
答案 2 :(得分:0)
根据您的测试代码(和其他答案):
SET LANGUAGE Spanish
DECLARE @date nvarchar(30)
SET @date = '12 of enero of 2012'
PRINT @date
PRINT cast(REPLACE(@date, 'of', '') as datetime)