简体   繁体   English

将十进制转换为日期以便使用DATENAME函数

[英]Convert decimal to date in order to use DATENAME function

Working with an ERP database (SQL Server) that stores dates as decimal columns in YYYYMMDD format - eg 20160801 . 使用以YYYYMMDD格式(例如20160801 )将日期存储为小数列的ERP数据库(SQL Server)。 I need to convert these values into dates so that I can use the DATENAME function to identify the day of the week corresponding to each date. 我需要将这些值转换为日期,以便可以使用DATENAME函数标识与每个日期相对应的星期几。

Or, if there is another way to derive the day of the week, I am all ears. 或者,如果还有另一种方法可以得出星期几,那么我会不知所措。 The rest of the query is simple ... I just need to return an Order Number, the Order Date (the column stored as a decimal), and the day of the week corresponding to the Order Date. 查询的其余部分很简单...我只需要返回订单号,订单日期(以小数形式存储的列)以及对应于订单日期的星期几。

EDIT (taken from a comment) 编辑(摘自评论)

I am still missing something as I'm getting a could not be bound error: 我仍然缺少一些东西,因为我遇到了一个无法绑定的错误:

Select CAST(OEORDD.EXPDATE AS VARCHAR(8)) 
DECLARE @dec DECIMAL(10,0)=20160801; 
SELECT CAST(CAST(@dec AS VARCHAR(8)) AS DATE) , sum(OEORDD.EXTWEIGHT) as ExtWeight 
FROM OEORDD 
GROUP BY EXPDATE

There is the "unserparated" datetime format, which is casteable natively. 有一种“未分割的”日期时间格式,可以本地转换。 For this you'd need an 8-letter-string with yyyymmdd . 为此,您需要一个带有yyyymmdd的8个字母的字符串。

So first convert your decimal number to a string: 因此,首先将您的十进制数字转换为字符串:

CAST(YourDecimalValue AS VARCHAR(8))

Then cast this to a date: 然后将其转换为日期:

DECLARE @dec DECIMAL(10,0)=20160801;
SELECT CAST(CAST(@dec AS VARCHAR(8)) AS DATE)

UPDATE (concerning your comment) 更新(关于您的评论)

Might be you need something like this: 您可能需要这样的东西:

SELECT  CAST(CAST(OEORDD.EXPDATE AS VARCHAR(8)) AS DATE) AS YourConvertedDate
       ,SUM(OEORDD.EXTWEIGHT) AS ExtWeight 
FROM OEORDD 
GROUP BY CAST(CAST(OEORDD.EXPDATE AS VARCHAR(8)) AS DATE)

You can use it for Text or Number of a week day: 您可以将其用于文本或星期几:

DECLARE @d DECIMAL = 20160801;
SELECT DATENAME(dw,CAST(CAST(@d as VARCHAR(8)) as DATE)),
    DATENAME(d,CAST(CAST(@d as VARCHAR(8)) as DATE)),
    @d;
DECLARE @decimal DECIMAL(10,0)=20160801;
SELECT DATENAME(dw,CAST(convert(VARCHAR(8),@decimal) AS DATE))

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

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