简体   繁体   English

MS SQL-DB2表

[英]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. 我已经使用substr从yyyymmdd数字字符串中将SQL中的DB2日期转换为mm / dd / yyyy,这是我们想要的格式。 Problem is still not recognized as a 'true' date to do calculations on such as datedif. 问题仍然不被认为是对“ datedif”进行计算的“真实”日期。

How do I change the mm/dd/yyyy new format to a true date field? 如何将mm / dd / yyyy新格式更改为真实的日期字段? 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: 要将mm / dd / yyyy字符串转换为真实日期,请使用:

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). 我必须假设您的问题中的“ SQL”表示Microsoft SQL Server(我不知道MS拥有“ SQL”)。 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. 因此,如果您从YYYYMMDD格式的DB2中获取字符串,则它是在SQL Server中转换为“实际日期”的最安全格式。

So, when reading into a SQL Sever table do this: (112 is a "style" for YYYYMMDD) 因此,当读入SQL Sever表时,请执行以下操作:(112是YYYYMMDD的“样式”)

convert(datetime, your_DB2_date_string_here ,112)

where you see "datetime" above note you can use different types in SQL Server: 您在上面的注释中看到“ datetime”的地方,可以在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 对于“实际日期字段”的输出,可以再次使用convert函数,或者如果您具有SQL 2012或更高版本,则可以使用format()函数

for output as MM/DD/YYYY use 用于输出为MM / DD / YYYY

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 请参阅: http : //msdn.microsoft.com/zh-CN/library/ms187928( v= sql.100).aspx http://www.sql-server-helper.com/sql-server-2012/format-功能VS转换功能.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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