在 SQL 表中插入日期值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46312391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert date value in SQL table
提问by terrifurness
I have the following table :
我有下表:
EMPNO(number), ENAME(varchar), JOB(char), MGR(number), HIREDATE(date), SAL(number), DEPTNO(number)
I try to insert the following :
我尝试插入以下内容:
insert into EMP_TF1605(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO)
values(7369, 'SMITH', 'CLERK', 7902, 17-DEC-1980, 800, 20);
Result : Error occured. Recheck your SQL statement
结果:发生错误。重新检查您的 SQL 语句
I am sure it is the date that is incorrect?
我确定这是不正确的日期?
回答by zarruq
Always use ANSI
default string literal format for date
i.e. YYYY-MM-DD
like below.
始终使用ANSI
默认的字符串文字格式,date
即YYYY-MM-DD
像下面。
INSERT INTO EMP_TF1605(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO)
VALUES(7369,
'SMITH',
'CLERK',
7902,
'1980-12-17',
800,
20);
It will insert your data successfully in most rdbms i.e. MySQL, PostgreSQL, SQL Server.
它将在大多数 rdbms 中成功插入您的数据,例如 MySQL、PostgreSQL、SQL Server。
In Oracle, you need to convert it to date
using function to_date([value],[format]
prior to insertion as below.
在 Oracle 中,您需要在插入之前将其转换为date
using 函数to_date([value],[format]
,如下所示。
INSERT INTO EMP_TF1605(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO)
VALUES(7369,
'SMITH',
'CLERK',
7902,
to_date('1980-12-17', 'yyyy-mm-dd'),
800,
20);
However if your input date is in format mentioned in question, you can use cast
in SQL Server to convert it to datetime
before insertion as below.
但是,如果您的输入日期是有问题的格式,您可以cast
在 SQL Server 中使用将其转换为datetime
插入前,如下所示。
INSERT INTO EMP_TF1605(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO)
VALUES(7369,
'SMITH',
'CLERK',
7902,
cast('17-Dec-1980' AS datetime),
800,
20);
For other rdbms, you need to look for the equivalent casting functions.
对于其他 rdbms,您需要寻找等效的转换函数。
Update:
更新:
In Oracle, for the date format provided in question, you can use to_date
to convert your string date literal input along using format 'DD-MON-YYYY'
to data type date
.
在 Oracle 中,对于所提供的日期格式,您可以使用 formatto_date
将字符串日期文字输入转换'DD-MON-YYYY'
为 data type date
。
TO_DATE('20-SEP-2017', 'DD-MON-YYYY')
You can check demos i.e. MySQL, PostgreSQL, SQL Server, Oracle
您可以查看演示,即MySQL、PostgreSQL、SQL Server、Oracle
回答by Callixte F
It works for me in SQL management studio if I use this syntax :
如果我使用以下语法,它在 SQL management studio 中对我有用:
ALTER TABLE tablename
ADD Report_Date datetime NULL;
GO
Update tablename set Report_Date = cast('2020-01-20' AS datetime)
as zarruqsaid previously.
正如zarruq之前所说。