Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 从sql查询生成json_Sql Server_Json_Algorithm_Typescript - Fatal编程技术网

Sql server 从sql查询生成json

Sql server 从sql查询生成json,sql-server,json,algorithm,typescript,Sql Server,Json,Algorithm,Typescript,我有以下情况: class question { idQuestion: string; question: string; type: string; } class options { idOption: string; option: string; } 我的SQL返回: idquestion question type idoption option i、 e: 我想将SQL响应映射到以下接口: questionOptions{ qu

我有以下情况:

class question {
    idQuestion: string;
    question: string;
    type: string;
}

class options {
    idOption: string;
    option: string;
}
我的SQL返回:

idquestion question type idoption option
i、 e:

我想将SQL响应映射到以下接口:

questionOptions{
    question: Question;
    options: Option[];
}
我怎样才能做到这一点?所以最后,我可以有一个问题列表,每个问题都有自己的选择

附言:在问题和sql数据库中的选项之间建立关联是更好的选择吗

编辑:

从示例数据中,我希望获得以下json:

[
  {
    idQuestion: "question1",
    question: "foo?",
    options: []
  },
  {
    idQuestion: "question2",
    question: "bar?"
    options: [
      {
        idOption: "option1",
        option: "aaa"
      },
      {
        idOption: "option2",
        option: "bbb"
      },
    ]
  }
]

我有一个helper函数,它可以将几乎任何行/数据集转换为JSON字符串/数组

假设2012年+

Declare @YourData table (idQuestion varchar(50),question varchar(50), type varchar(50),idOption varchar(50),[option] varchar(50))
Insert Into @YourData values
('question1','foo?','textbox', null, null),
('question2','bar?','select','option1','aaa'),
('question2','bar?','select','option2','bbb'),
('question3','foobar?','radio','option1','aaa'),
('question3','foobar?','radio','option2','bbb'),
('question3','foobar?','radio','option3','ccc')


Declare @JSON varchar(max) = ''
Select @JSON=@JSON+','+String
 From  (
        Select String=Replace(B.JSON,'}',',"options":'+IsNull(C.JSON,'[]')+'}')
         From (Select Distinct idquestion,question From @YourData) A
         Cross Apply (Select JSON=[dbo].[udf-Str-JSON](0,0,(Select A.idQuestion,A.question  for XML RAW))) B
         Cross Apply (Select JSON=[dbo].[udf-Str-JSON](0,0,(Select idOption,[option] from @YourData Where idquestion=A.idquestion  for XML RAW))) C
       ) A

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

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)
CREATE FUNCTION[dbo].[udf Str JSON](@IncludeHead int、@ToLowerCase int、@XML)
返回varchar(最大值)
作为
开始
声明@Head varchar(max)='',@JSON varchar(max)=''
; 将cteEAV设置为(选择RowNr=行号()覆盖(订单编号(选择NULL))
,Entity=xRow.value('@*[1]','varchar(100)'
,Attribute=xAtt.value('local-name(.)','varchar(100)'
,Value=xAtt.Value('.','varchar(max)'
从@XML.nodes('/row')作为R(xRow)
交叉应用R.xRow.nodes('./@*')作为(xAtt))
,cteSum as(选择记录=计数(不同实体)

,Head=IIF(@IncludeHead=0,IIF(计数(独立实体)什么版本的SQL Server?2016引入了对JSON的支持,这可能有助于在查询中正确格式化您的输出。通过示例数据,提供实际需要的JSON。我可能有一些需要改进的地方help@alroc我们有SQL server2014@JohnCappelletti我更新了我的answer@ArnaldoAntonioTorres见刚才补充的答案
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)