0

Se tiene la siguiente consulta para exportarla a un Archivo JSon

SELECT  periodo, tipo, tipoDia, p
 FROM  registrar.tiempoPeriodo tp
 where frtID='hkt00010' and periodo >= '2019-11-10'
      and tp.tipo in ('ValorTipicoInicial', 'ValorTipico ')
      and tp.periodo = (select MAX(vers.periodo)
          from registrar.tiempoPeriodo vers
          where vers.frtID = ct.frtID
          and vers.tipoDia = ct.tipoDia)
  FOR JSON path, ROOT('QryTiempoPeriodo')

Guiandome con las instrucciones de esta página

pero al tratar de realizar o llamar la instrucción sale un error en la consulta

introducir la descripción de la imagen aquí

sale incorrect syntax error near JSON

5
  • 1
    Que versión de SQL Server estás usando? Aparentenmente esa sintaxis está disponible desde Sql Server 2016.
    – Asero82
    el 14 nov. 2019 a las 13:07
  • @Asero82 la version es SQL 2014
    – ger
    el 14 nov. 2019 a las 14:48
  • @ger Entonces la instrucción FOR JSON no está disponible. Puedes utilizar las rutinas creadas por Phil Factor el 14 nov. 2019 a las 15:48
  • @Asero82 a partir de que versión está disponible For JSON???
    – ger
    el 14 nov. 2019 a las 15:54
  • @Asero82 lo que me pasaste es para SQL server 2008, en 2014 no funciona!
    – ger
    el 14 nov. 2019 a las 16:08

1 respuesta 1

0

Al fin encontre la solucion para esto en SQL Server

Declare @XML   xml = (SELECT  periodo, tipo, tipoDia, p
 FROM  registrar.tiempoPeriodo tp
 where frtID='hkt00010' and periodo >= '2019-11-10'
   and tp.tipo in ('ValorTipicoInicial', 'ValorTipico ')
   and tp.periodo = (select MAX(vers.periodo)
      from registrar.tiempoPeriodo vers
      where vers.frtID = ct.frtID
      and vers.tipoDia = ct.tipoDia)  for XML RAW)
  Declare @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 A(xRow)
   Cross Apply A.xRow.nodes('./@*') As B(xAtt) )
 ,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('"',Attribute,'":','"',Value,'"')
   From  cteEAV )
Select @JSON = @JSON+NewRow+JSON+EndRow
 From  cteBld 

Select '['+Stuff(@JSON,1,1,'')+']'

Fuente: lo encontré en en este hilo en inglés

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.