I have this query on SQL Server, the goal of this query is to set the milliseconds to 000, for instance,
Before this Query: 2017-06-01 11:53:00.123
After: 2017-06-01 11:53:00.000
UPDATE table1
SET ValidFrom = CONVERT(DATETIME, CONVERT(CHAR(19), ValidFrom, 126))
WHERE ValidFrom IS NOT NULL;
ValidFrom is a column on the database that it is a datetime.
There is a Convert command on Oracle but it doesn't work with Datetime.
How can I translate this to Oracle?
date
, datetime
, datetimeoffset
, etc column to char
/ varchar
is a code-smell and a strong hint that you're doing something wrong because you should never need to format-dates to perform date/time processing in SQL.datetime
type like SQL Server does, instead it has a timestamp
type (which has absolutely nothing to do with SQL Server's own timestamp
type which is an alias for rowversion
but I digress). timestamp
type is parameterised to specify the amount of precision for sub-second resolution - so simply CAST
ing your value to timestamp(0)
will effectively zero-out the milliseconds component. EXTRACT
function to obtain the integer value ( 0-999
) of the milliseconds component of a timestamp
value.UPDATE
table
SET
ValidFrom = CAST( ValidFrom AS timestamp(0) )
WHERE
ValidFrom IS NOT NULL
Here's a working demo in SQLFiddle, using Oracle 11g R2 :
Build Schema Script:
CREATE TABLE testTable (
ValidFrom timestamp(7) NOT NULL
);
INSERT INTO testTable ( ValidFrom )
WITH v AS (
SELECT TIMESTAMP '1997-01-08 11:11:11.111' AS ts FROM dual UNION ALL
SELECT TIMESTAMP '1997-02-09 12:22:22.222' AS ts FROM dual UNION ALL
SELECT TIMESTAMP '1997-03-10 13:33:33.333' AS ts FROM dual UNION ALL
SELECT TIMESTAMP '1997-04-11 14:44:44.444' AS ts FROM dual
)
SELECT ts FROM v
Query script:
SELECT
ValidFrom,
CAST( ValidFrom AS timestamp(0) ) AS ValidFrom_withoutMilliseconds,
( ValidFrom - CAST( ValidFrom AS timestamp(0) ) ) AS diff
FROM
testTable
//
UPDATE
testTable
SET
ValidFrom = CAST( ValidFrom AS timestamp(0) )
WHERE
ValidFrom IS NOT NULL
//
SELECT
ValidFrom,
CAST( ValidFrom AS timestamp(0) ) AS ValidFrom_withoutMilliseconds,
( ValidFrom - CAST( ValidFrom AS timestamp(0) ) ) AS diff
FROM
testTable
//
is the query separator, which is separate from the "query terminator" in Oracle.EXTRACT
, fortunately that isn't necessary for this query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.