简体   繁体   English

SQL中的日期时间类型转换

[英]Datetime type conversion in SQL

I am getting data from some external datasource and need to store in SQL server table. 我从某个外部数据源获取数据,并且需要存储在SQL Server表中。 But one filed in it is Datetime. 但其中提起的是日期时间。 But I am getting that datetime field as Varchar format, and now in my SQL table I need to save it as DateTime datatype. 但是我将日期时间字段获取为Varchar格式,现在在我的SQL表中,需要将其保存为DateTime数据类型。

CONVERT(DATETIME,[Date_time],03) 

-- This code work in my Development Environment but not in Production. -此代码在我的开发环境中有效,但在生产环境中无效。

CONVERT(DATETIME,[Date_time],120) 

-- This code work in my Production but not in development. -此代码在我的生产环境中有效,但在开发中无效。

This make my life difficult to transfer code from development to Production since I have to make changes in tested code. 这使我很难将代码从开发转移到生产,因为我必须对经过测试的代码进行更改。

Please note that I am using SQL server 2008 R2. 请注意,我正在使用SQL Server 2008 R2。

Is there anyway that I can make code similar? 无论如何,我可以使代码相似吗? I cannot change the culture and language on both server since many other applications are deployed there and it might break existing application in both server. 我无法更改两台服务器上的文化和语言,因为许多其他应用程序已部署在该服务器上,并且可能会破坏两台服务器上的现有应用程序。

A workaround for your problem would be to provide a feature that calculates (or defines) the correct style for each environment. 解决该问题的方法是提供一种功能,该功能可以计算(或定义)每种环境的正确样式。 This simplest option would be a user-defined function. 这个最简单的选项是用户定义的函数。

CREATE FUNCTION [dbo].[fnCustomDateStyle]()
RETURN int AS
BEGIN
  RETURN 3 # Or 120, in the other environment
END

Which can be used in every environment thus: 因此可以在每种环境中使用:

CONVERT(DATETIME, [Date_Time], fnCustomDateStyle())

You can try to use a SET statement to override the date format, something like this: 您可以尝试使用SET语句覆盖日期格式,如下所示:

SET DATEFORMAT mdy;
SELECT CONVERT(DATETIME, [Date_Time], 120);

As long as you include this code in your stored procedure/query on both environments, this should be fine. 只要您在两种环境中的存储过程/查询中都包含此代码,就可以了。 You may want to read up about this on MSDN . 您可能想在MSDN上阅读有关此内容。

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

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