简体   繁体   English

SQL Server在查询之前执行日期转换

[英]SQL server perform date conversion before querying

I have an application which returns the date in the format: "Thu Sep 22 2016" and I want to query sql server database which has stored the date in the format "2016-09-06". 我有一个应用程序以“ Thu Sep 22 2016”格式返回日期,并且我想查询以“ 2016-09-06”格式存储日期的SQL Server数据库。 Does SQL server provide any built-in function for conversion (specially the 3 letter month name to number)? SQL Server是否提供任何内置函数进行转换(特别是将3个字母月份的名称转换为数字)? Please let me know. 请告诉我。

SQL Server has limited date conversion support. SQL Server具有有限的日期转换支持。 These are described in the documentation . 这些在文档中进行了描述。

I think this does what you want: 我认为这可以满足您的需求:

select convert(date, substring(col, 5, 6) + ',' + right(col, 5), 107)

The idea is to convert your string to "Sep 22, 2016" and then use this for the conversion. 想法是将您的字符串转换为“ 2016年9月22日”,然后将其用于转换。 Assuming your internationalization formats are set to English, then this approach should work. 假设您的国际化格式设置为英语,则此方法应该有效。

You can use FORMAT 您可以使用FORMAT

Example: 例:

DECLARE @d DATETIME = '10/01/2011';  
SELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result'  
      ,FORMAT ( @d, 'd', 'en-gb' ) AS 'Great Britain English Result'  
      ,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result'  
      ,FORMAT ( @d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC) Result';   

SELECT FORMAT ( @d, 'D', 'en-US' ) AS 'US English Result'  
      ,FORMAT ( @d, 'D', 'en-gb' ) AS 'Great Britain English Result'  
      ,FORMAT ( @d, 'D', 'de-de' ) AS 'German Result'  
      ,FORMAT ( @d, 'D', 'zh-cn' ) AS 'Chinese (Simplified PRC) Result';  

尝试这个:

SELECT STR_TO_DATE('Sep 22, 2016','%M %d,%Y');

The only thing you have to do is to remove the day of the week part of your string date format. 您唯一要做的就是删除字符串日期格式的星期几部分。 Once that is removed, the string is in a standard date format for SQL Server. 删除后,该字符串将采用SQL Server的标准日期格式。

Declare @yourTable table (
    Id int identity(1,1),
    YourDate  datetime2
)

Insert into @yourTable values 
('2016-09-22'),
('2016-09-16'),
('2016-09-22')

Declare @appDate varchar(100) = 'Thu Sep 22 2016'
Set @appDate = ltrim(substring(@appDate,4,len(@appDate)-3))
select * from @yourTable where cast(YourDate as date) = @appDate

I also converted the datetime in the table to date to avoid using the time component of the datetime when querying. 我还将表中的datetime转换为date,以避免在查询时使用datetime的时间分量。

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

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