【问题标题】:generating json from bad mysql-formatted dates in asp从asp中错误的mysql格式日期生成json
【发布时间】:2017-03-31 12:33:28
【问题描述】:

我被投入了一个新项目,这显然不仅仅是过时的。该应用程序以一种非常奇怪的模式在数据库中保存了开放时间,这让我疯狂了一个多星期。

请看这张图片:

如您所见,营业时间以如下模式保存:

dayFrom  | dayTo  | timeFrom | timeTo 
=======================================
monday   | friday | 07:00    | 17:00
saturday |        | 08:00    | 12:00

只是为了防止任何误解:

周一至周五 07:00 至 17:00 开放

从 08:00 到 12:00 开放 SA

周日休息

现在,这似乎已经有点不对了,但坚持下去,表格可能看起来像这样:

dayFrom   | dayTo   | timeFrom | timeTo 
=======================================
monday    | tuesday | 07:00    | 14:00
wednesday |         | 08:00    | 12:00
thursday  | friday  | 07:30    | 13:00
saturday  |         | 08:00    | 12:00

所以,现在我的问题是:我需要创建一个循环(或类似的东西)来创建一个有效的 json 字符串,其中包含所有这些开放时间。

现在,我有这个:

jsonAppendix = "{""openingHours"":["
for i = 1 To cint(hoechsterTag)
    jsonAppendix = jsonAppendix & "{""dayOfWeek"":" & i & ", ""from1"":""" & rs("ZeitVon") & """, ""to1"":""" & rs("ZeitBis") & """},"
next
'Remove last comma
jsonAppendix = LEFT(jsonAppendix, (LEN(jsonAppendix)-1))
jsonAppendix = jsonAppendix & "]}"

如果我只有“周一至周五”,它已经可以使用,但不考虑第二个(或下一个条目)。

输出看起来像这样,这显然是正确的:

{
    "openingHours":[
        {
            "dayOfWeek":1,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":2,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":3,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":4,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":5,
            "from1":"07:00",
            "to1":"17:00"
        }
    ]
}

但是“星期六”没有被识别。

我的函数如下所示:

SQL = "SELECT * FROM StandortOpen WHERE S_ID = " & iStandortId & " AND OpenArt = '" & sArt & "' ORDER BY Sort,OpenArt DESC"
call openRS(SQL)    

'day-mapping
tageV(0) = replace(rs("TagVon"),"Mo", 1)
tageV(1) = replace(rs("TagVon"),"Di", 2)
tageV(2) = replace(rs("TagVon"),"Mi", 3)
tageV(3) = replace(rs("TagVon"),"Do", 4)
tageV(4) = replace(rs("TagVon"),"Fr", 5)
tageV(5) = replace(rs("TagVon"),"Sa", 6)
tageV(6) = 7

tageB(0) = replace(rs("TagBis"),"Mo", 1)
tageB(1) = replace(rs("TagBis"),"Di", 2)
tageB(2) = replace(rs("TagBis"),"Mi", 3)
tageB(3) = replace(rs("TagBis"),"Do", 4)
tageB(4) = replace(rs("TagBis"),"Fr", 5)
tageB(5) = replace(rs("TagBis"),"Sa", 6)


'for example: mo - fr   
for each item in tageV
    'save smallest weekday
    if(isNumeric(item) AND item > "") then
        if(cint(item) <= cint(niedrigsterTag)) then
            niedrigsterTag = cint(item)
        end if
    end if
next    

for each item in tageB
    'save highest weekday
    if(isNumeric(item) AND item > "") then
        if(cint(item) >= cint(hoechsterTag)) then
            hoechsterTag = cint(item)
        end if
    end if
next    

还有openRS()-函数:

sub openRS(str_sql)
'Response.write "SQL: " & str_sql & "<br>"
set rs = CreateObject("ADODB.Recordset")
rs.open str_sql,conn,1,3
end sub

基本上:将数字映射到日期,迭代(或比较它们以获得时间跨度)。

我也在使用RecordSet。也许我需要使用数组或类似的东西?任何帮助将不胜感激。

我不能改变桌子和它的设计,我必须坚持那个gargabe

【问题讨论】:

    标签: sql json tsql vbscript asp-classic


    【解决方案1】:

    如果要在 SQL Server 中创建数据集,请考虑以下事项

    示例

    Declare @YourTable table (dayFrom varchar(25),dayTo varchar(25),timeFrom varchar(25),timeTo varchar(25))
    Insert Into @YourTable values
    ('monday'   ,'tuesday','07:00','14:00'),
    ('wednesday',''       ,'08:00','12:00'),
    ('thursday' ,'friday' ,'07:30','13:00'),
    ('saturday' ,''       ,'08:00','12:00')
    
    ;with cteD as (Select * From (Values(1,'Monday'),(2,'Tuesday'),(3,'Wednesday'),(4,'Thursday'),(5,'Friday'),(6,'Saturday'),(7,'Sunday')) DDD(DD,DDD) ),
          cteR as (
                    Select A.*
                          ,R1 = B.DD
                          ,R2 = IsNull(C.DD,B.DD)
                     From  @YourTable A
                     Left Join cteD B on dayFrom = B.DDD
                     Left Join cteD C on dayTo   = C.DDD
                     Where 1=1  -- Your WHERE STATEMENT HERE
                  )
     Select daySeq    = A.DD
           ,dayOfWeek = A.DDD
           ,from1     = IsNull(B.TimeFrom,'Closed')
           ,from2     = IsNull(B.TimeTo,'Closed')
     From   cteD A
     Left Join   cteR B on A.DD between B.R1 and B.R2
     Order By 1
    

    退货

    注意:关闭是可选的。删除最终查询中的“LEFT”联接

    现在,如果您想在 SQL Server 中创建 JSON 字符串,并且您不在 2016 年,我们可以调整最终查询并添加 UDF。

    Select JSON=[dbo].[udf-Str-JSON](0,0,(
         Select daySeq    = A.DD
               ,dayOfWeek = A.DDD
               ,from1     = IsNull(B.TimeFrom,'Closed')
               ,from2     = IsNull(B.TimeTo,'Closed')
         From   cteD A
         Left Join   cteR B on A.DD between B.R1 and B.R2
         Order By 1
         For XML RAW
    ))
    

    返回的 JSON 字符串

    [{
        "daySeq": "1",
        "dayOfWeek": "Monday",
        "from1": "07:00",
        "from2": "14:00"
    }, {
        "daySeq": "2",
        "dayOfWeek": "Tuesday",
        "from1": "07:00",
        "from2": "14:00"
    }, {
        "daySeq": "3",
        "dayOfWeek": "Wednesday",
        "from1": "08:00",
        "from2": "12:00"
    }, {
        "daySeq": "4",
        "dayOfWeek": "Thursday",
        "from1": "07:30",
        "from2": "13:00"
    }, {
        "daySeq": "5",
        "dayOfWeek": "Friday",
        "from1": "07:30",
        "from2": "13:00"
    }, {
        "daySeq": "6",
        "dayOfWeek": "Saturday",
        "from1": "08:00",
        "from2": "12:00"
    }, {
        "daySeq": "7",
        "dayOfWeek": "Sunday",
        "from1": "Closed",
        "from2": "Closed"
    }]
    

    有兴趣的 UDF

    CREATE FUNCTION [dbo].[udf-Str-JSON] (@IncludeHead int,@ToLowerCase int,@XML xml)
    Returns varchar(max)
    AS
    Begin
        Declare @Head varchar(max) = '',@JSON varchar(max) = ''
        ; with cteEAV as (Select RowNr     =Row_Number() over (Order By (Select NULL))
                                ,Entity    = xRow.value('@*[1]','varchar(100)')
                                ,Attribute = xAtt.value('local-name(.)','varchar(100)')
                                ,Value     = xAtt.value('.','varchar(max)') 
                           From  @XML.nodes('/row') As R(xRow) 
                           Cross Apply R.xRow.nodes('./@*') As A(xAtt) )
              ,cteSum as (Select Records=count(Distinct Entity)
                                ,Head = IIF(@IncludeHead=0,IIF(count(Distinct Entity)<=1,'[getResults]','[[getResults]]'),Concat('{"status":{"successful":"true","timestamp":"',Format(GetUTCDate(),'yyyy-MM-dd hh:mm:ss '),'GMT','","rows":"',count(Distinct Entity),'"},"retults":[[getResults]]}') ) 
                           From  cteEAV)
              ,cteBld as (Select *
                                ,NewRow=IIF(Lag(Entity,1)  over (Partition By Entity Order By (Select NULL))=Entity,'',',{')
                                ,EndRow=IIF(Lead(Entity,1) over (Partition By Entity Order By (Select NULL))=Entity,',','}')
                                ,JSON=Concat('"',IIF(@ToLowerCase=1,Lower(Attribute),Attribute),'":','"',Value,'"') 
                           From  cteEAV )
        Select @JSON = @JSON+NewRow+JSON+EndRow,@Head = Head From cteBld, cteSum
        Return Replace(@Head,'[getResults]',Stuff(@JSON,1,1,''))
    End
    -- Parameter 1: @IncludeHead 1/0
    -- Parameter 2: @ToLowerCase 1/0 (converts field name to lowercase
    -- Parameter 3: (Select * From ... for XML RAW)
    -- Syntax : Select [dbo].[udf-Str-JSON](0,1,(Select Top 2 RN=Row_Number() over (Order By (Select NULL)),* from [Chinrus-Shared].[dbo].[ZipCodes] Where StateCode in ('RI') for XML RAW))
    /*
    Declare @User table (ID int,Active bit,First_Name varchar(50),Last_Name varchar(50),EMail varchar(50))
    Insert into @User values
    (1,1,'John','Smith','john.smith@email.com'),(2,0,'Jane','Doe'  ,'jane.doe@email.com')
    
    Declare @XML xml = (Select * from @User for XML RAW)
    Select A.ID
          ,B.JSON
     From  @User A
     Cross Apply (Select JSON=[dbo].[udf-Str-JSON](0,0,(Select A.* For XML Raw)) ) B
    */
    

    【讨论】:

    • 非常感谢约翰。我会在星期一试试这个,会给你反馈。感谢您的努力。这看起来很有希望!
    • 只是一个简短的提醒 - 我将在这一天给你反馈。我不知道你为什么被否决,但我的问题也是如此。
    • @DasSaffe 不是我的第一个 dv,也不会是我的最后一个。我宁愿他们有勇气发表评论。 --- 期待您的反馈
    • 这似乎正是我正在寻找的东西(从你的截图来看)——但我在将它转移到我的案例时遇到了问题。你介意加入聊天吗? (如果我能弄清楚如何创建一个)?
    • @DasSaffe 我从未发起过聊天。给我一点时间找到它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多