search
HomeDatabaseMysql TutorialSQL Server,MySQL,Oracle,PostgreSQL中常用函数用法(1)日

练习使用Hibernate没有用MySQL数据库,而是用了前不久接触的PostgreSQL,由于不同的数据对于相同的操作有各自的函数,MySQL的date_format(),在PostgreSQL中是没有的,google一番发现原来是要用to_char()。 搜索到一篇英文文章《Executing Common SQL Coding

         练习使用Hibernate没有用MySQL数据库,而是用了前不久接触的PostgreSQL,由于不同的数据对于相同的操作有各自的函数,MySQL的date_format(),在PostgreSQL中是没有的,google一番发现原来是要用to_char()。

        搜索到一篇英文文章《Executing Common  SQL Coding Tasks Using Function Calls》(常用SQL函数调用的区别),其中列出了如:MS SQL Server、MySQL、Oracle、PostgreSQL,这几个常用数据库中的常用函数。

        边翻译加自己的补充,分成几个文章共享给大家。方便以后的使用。

日期操作

 

1. 获取当前日期和时间

  • SQL Server

getdate()函数   (返回当前的日期和时间)

<span>SELECT GETDATE()
GO</span>


  •  MySQL

curdate()函数(返回当前的日期)

now()函数 (返回当前的日期和时间)

<span>SELECT CURDATE()

</span>
  • Oracle

sysdate (返回服务器时间)

<span>SELECT SYSDATE 
FROM dual;
</span>
  • PostgreSQL

current_date (返回当天的日期)

current_timestamp  (返回日期和时间)

now()  (返回当前的日期和时间,等效于 current_timestamp)

<span>SELECT CURRENT_DATE;
</span>


【注意】

  1. 以上的函数都是不需要参数的。
  2. Oraclecurrent_datesysdate都是现实当前时间,结果基本相同,但是也有区别:
      a.  urrent_date返回的是当前会话时间,sysdate
    返回的是服务器时间。
     b. current_date有时候比sysdate
    快一秒,这可能是四舍五入的结果。
     c. 如果修改当前会话的时区,比如将中国的时区为东八区,修改为东九区,则current_date显示的时间为东九区时间,根据东加西减的原则,current_date应该比sysdate快一小时.


2. 操作时间的获取子域。比如:年、月、日、小时等等。

  • SQL Server:datepart(datepart,date)
SELECT DATEPART(dw, GETDATE())
GO

*  datepart()函数可以方便的取到日期中的各个部分,如日期:2012-12-05 151536.513


yy 取年:2012
mm 取月:12
dd 取月中的天:5
dy 取年中的天:340
wk 取年中的周:50
dw 取周中的天:4
qq 取年中的季度:4
hh 取小时:15
mi 取分钟:15
ss 取秒:36


  • MySQL:dayofmonth(date)返回对应的工作日名称
SELECT DAYNAME('1998-02-03');
->'周四'

  • Oracle:to_char(date,'格式')

SELECT TO_CHAR(SYSDATE, 'Day') 
FROM dual;

  • PostgreSQL:date_part(text,timestamp)

SELECT DATE_PART('dow', date 'now');


3. 两个时间的间隔

  • SQLServer

SELECT DATADIFF(dd,'1/1/01',GETDATE())
GO

  • MySQL

SELECT FROM_DAYS(TO_DAYS(CURDATE()) - TO_DAYS('2012-12-05'));

  • Oracle

SELECT TO_DATE('25-Nov-2000','dd-mon-yyyy') - TO_DATE('25-Aug-1969','dd-mon-yyyy')
FROM dual;

  • PostgreSQL

SELECT AGE(CURRENT_DATE,'25-Aug-1969');


4. 日期格式化(Mon,DD,YYYY;mm/dd/yy;dd/mm/yy;等等)

  • SQL Server

SELECT CONVERT(VARCHAR(11),GETDATE(),102)
GO

  • MySQL

SELECT DATE_FORMAT("2001-11-25","%M %E,%Y");

  • Oracle

ELECT TO_CHAR(SYSDATE,'dd-Mon-yyyy hh:mi,ss PM')
FROM dual;

  • PostgreSQL

SELECT TO_CHAR(timestamp(CURRENT_DATE),'dd-Mon-yyyy hh:mi:ss PM')



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)