Sql-Server-2016
從 char(26) 轉換為 datetime2
在更改過程中,我將數據庫從 Oracle 12.1 遷移到 MSSQL 2016。由於兩個數據庫處理日期的方式不同,我現在需要將欄位從 char(26) 移動到 datetime2。輸出格式例如
2011-05-30-13.06.56.824000
我需要的是 Type 21:2016-04-01 10:20:56.8950000
。我已經嘗試過使用SELECT CONVERT( DATETIME2 ,LEFT (EXP_DATE ,10) + "" + REPLACE (SUBSTRING(EXP_DATE ,12 ,8) ,"." ,":") + RIGHT(EXP_DATE ,7) ,21 ) AS DateFromString FROM My-TABLE;
但這不起作用(列名錯誤):
消息 207,級別 16,狀態 1,第 1 行無效的列名“”。
消息 207,級別 16,狀態 1,第 1 行 列名“.”無效。
消息 207,級別 16,狀態 1,第 1 行 列名“:”無效。
有人能幫我嗎?
您應該通過單引號更改雙引號。
'.', ':'
CREATE TABLE MyTable(EXP_DATE varchar(26)); INSERT INTO MyTable (EXP_DATE ) VALUES ('2011-05-30-13.06.56.824000'); GO
1 行受影響
SELECT CONVERT(datetime2, CONCAT(LEFT (EXP_DATE, 10), ' ', REPLACE (SUBSTRING (EXP_DATE, 12, 8), '.', ':'), RIGHT (EXP_DATE, 7)), 21) FROM MyTable; GO
| (無列名) | | :------------------ | | 30/05/2011 13:06:56 |
dbfiddle在這裡
DECLARE @table_name VARCHAR(100) -- table name DECLARE @column_name VARCHAR(100) -- table name DECLARE @value VARCHAR(100) -- table name DECLARE @path VARCHAR(256) -- path for backup files DECLARE @strSQL NVARCHAR(2000) DECLARE @msg NVARCHAR(2000) DECLARE @read_only INT DECLARE db_cursor CURSOR FOR SELECT c.table_name [Table Name], c.column_name [Column Name] FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t ON c.table_name = t.table_name WHERE c.data_type = 'char' AND c.column_name in ('DATCRE','DATCHG') AND c.CHARACTER_MAXIMUM_LENGTH = 26 AND t.table_type = 'BASE TABLE'; OPEN db_cursor FETCH NEXT FROM db_cursor INTO @table_name, @column_name WHILE @@FETCH_STATUS = 0 BEGIN SELECT @strSQL = 'UPDATE t SET ' + @column_name + ' = SUBSTRING(tt.' + @column_name + ',1,10) + '' '' + replace(SUBSTRING(tt.' + @column_name + ',12,8),''.'','':'') + SUBSTRING(tt.' + @column_name + ',20,7) FROM vmtest.dbo.' + @table_name + ' t INNER JOIN vmtest.dbo.' + @table_name + ' tt ON t.' + @column_name + ' = tt.' + @column_name + ';' SELECT @msg = 'Update Skript = ' + CAST(@strSQL as varchar(max)); RAISERROR(@msg, 0, 1) WITH NOWAIT; EXEC sp_executesql @strSQL; SET @strSQL = 'alter table ' + @table_name + ' alter column ' + @column_name + ' datetime2;' SELECT @msg = 'Alter Table = ' + CAST(@strSQL as varchar(max)); RAISERROR(@msg, 0, 1) WITH NOWAIT; EXEC sp_executesql @strSQL; FETCH NEXT FROM db_cursor INTO @table_name, @column_name END CLOSE db_cursor DEALLOCATE db_cursor