Azure流分析查询:将字符串转换为DateTime

时间:2018-01-24 05:57:58

标签: azure tsql datetime azure-stream-analytics

流分析的输入是IoT集线器,它将收到JSON消息。

数据

[
   {
      "deviceId": "testing",
      "id": "b8db8f582c474225b90b75dfed2e9c63",
      "username": "testing",
      "localtime": "24/01/2018 11:31:24",
      "b": 240,
      "e": 357,
      "AC": 0,
      "FM": 0,
      "UC": 0,
      "DL": 0,
      "DS": 0,
      "DP": 0,
      "DR": 0,
      "LB": 120,
      "ASTV": 73,
      "MSTV": 0.5,
      "ALTV": 43
   }
]

Azure Stream Analytics查询中,我使用CAST函数将localtime从string转换为datetime但是失败了。不允许使用CONVERT函数。

SELECT
    id as id,
    deviceId as deviceId,
    username as username,
    cast(localtime as datetime) as localtime,
    AC as AC, FM as FM, UC as UC, 
    DL as DL, DS as DS, DP as DP,
    LB as LB, ASTV as ASTV, MSTV as MSTV
FROM
    iot
  

无法输入值'24 / 01/2018 12:58:23'在表达式'cast(localtime as datetime)'中键入'datetime'

2 个答案:

答案 0 :(得分:0)

使用STRING FUNCTIONS,我们可以实现这一目标:

Azure Stream Analytics支持SUBSTRING功能。

SELECT
    id as id,
    deviceId as deviceId,
    username as username,
    CAST(SUBSTRING(localTime ,7 ,4)+'/'+SUBSTRING(localTime ,4 ,2)+'/'+SUBSTRING(localTime ,1 ,2)+SUBSTRING(localTime ,11 ,9) AS DATETIME) as localtime,
    AC as AC, FM as FM, UC as UC, 
    DL as DL, DS as DS, DP as DP,
    LB as LB, ASTV as ASTV, MSTV as MSTV
FROM
    iot;

希望这会有所帮助。

示例:

DECLARE @localTime VARCHAR(20)='24/01/2018 11:31:24'

SELECT CAST(SUBSTRING(@localTime ,7 ,4)+'/'+SUBSTRING(@localTime ,4 ,2)+'/'+SUBSTRING(@localTime ,1 ,2)+SUBSTRING(@localTime ,11 ,9) AS DATETIME)

<强>结果:

2018-01-24 11:31:24.000

答案 1 :(得分:0)

问题可能是localtime&#34; 24/01/2018 12:58:23&#34;有DD / MM / YYYY格式,你的工作使用期望MM / DD / YYYY的区域设置,所以问题是没有24个月。

您可以更改作业的区域设置,也可以使用JavaScript function解析具有特定区域设置的日期时间。