简体   繁体   中英

MS SQL - DB2 Tables

I have converted DB2 dates in SQL from yyyymmdd numeric string using substr to get mm/dd/yyyy which is the format we want. Problem is still not recognized as a 'true' date to do calculations on such as datedif.

How do I change the mm/dd/yyyy new format to a true date field? Have I made this more complicated then it has to be?

Try this....

select convert(datetime,yyyymmdd )

or

select Cast(yyyymmdd as datetime)

to convert a mm/dd/yyyy string to a true date use:

convert(datetime, your_nonDB2_date_string_here ,101)

more...

"Have I made this more complicated then it has to be?" Yes. Don't store dates as strings, it's really that simple.

I have to assume "SQL" in your question means Microsoft SQL Server (MS do not own "SQL" that I'm aware of). So if you are getting strings from DB2 in YYYYMMDD format this happens to be the safest format for conversion to "real dates" in SQL Server.

So, when reading into a SQL Sever table do this: (112 is a "style" for YYYYMMDD)

convert(datetime, your_DB2_date_string_here ,112)

where you see "datetime" above note you can use different types in SQL Server:

date --<< date only (no time)
smalldatetime
datetime
datetime2 --<< highest precision

For OUTPUT of a "real date field" you can use the convert function again, or if you have SQL 2012 or later you can use the format() function

for output as MM/DD/YYYY use

convert(varchar,real_date_field,101)

format(real_date_field,'MM/dd/yyyy') --<< nb case sensitive: MM not mm

see: http://msdn.microsoft.com/en-us/library/ms187928(v=sql.100).aspx http://www.sql-server-helper.com/sql-server-2012/format-function-vs-convert-function.aspx

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM