SQL - Insert json array into multiple tables with identity - sql

Here is the example json -
"Root Node - Type 1": {
"Attributes": {
"Items": [
{
"A": {
"Value": "A1"
},
"B": {
"Value": "B1"
},
"C": {
"Value": "C1"
},
"D": {
"Value": "D1"
}
},
{
"A": {
"Value": "A2"
},
"B": {
"Value": "B2"
},
"C": {
"Value": "C2"
},
"D": {
"Value": "D2"
}
}
]
}
}
I need to insert A, B in table 1 and take the identity from table 1 and insert into table 2. Also, I need to insert C, D into table 3. Items here will be a large array. I am looking to bulk insert this data into tables. Any ideas?
Table structure -
CREATE TABLE [Table 1](
[Id] [int] IDENTITY(1,1) NOT NULL,
[A] [varchar](100) NULL,
[B] [varchar](15) NULL,
[CreatedBy] [varchar](255) NULL,
[CreatedDate] [datetime] NULL
CREATE TABLE [Table 2](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Table1_Id] int,
[CreatedBy] [varchar](255) NULL,
[CreatedDate] [datetime] NULL
CREATE TABLE [Table 3](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Table1_Id] [int] NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Value] [nvarchar](1000) NULL
Data 0

Related

Insert Data from Json to multiple SQL tables with FK's

I want to get the data from a single JSON File to my SQL Database with multiple Tables.
This is the JSON File:
{
"Leads":
[
{
"id": "7dc31998-eb32-4171-a118-79837a2950ff",
"productId": "c7f3ba6f-5f8a-4472-8c03-000000000001",
"created": "2020-10-22T07:48:04.318123",
"customer": {
"city": "Hamburg",
"dateOfBirth": "1979-01-01",
"email": "max#mustermann.de",
"firstName": "max",
"netIncome": "FROM_1000_TO_1500",
"number": "123",
"occupation": "EMPLOYEE",
"phone": "+49 171 000 000 00",
"purchasePhase": "EVALUATING",
"street": "Spaldingstr.",
"surName": "mustermann",
"zip": "20097"
},
"request": {
"additionalCosts": 100000,
"brokerageFee": 0.068,
"city": "Stade",
"constructionType": "FOREIGN",
"cost": 500000,
"equity": 200000,
"financingRate": 0.066,
"kfwPromotion": true,
"loan": 400000,
"notaryFee": 0.02,
"realEstateTransferTax": 0.05,
"realEstateType": "APARTMENT",
"realEstateUsage": "RENT",
"zip": "21680"
}
},
{
"id": "7dc31205-eb32-4171-a118-79837a29abcd",
"productId": "c7f3ba6f-5f8a-4472-8c03-000000000001",
"created": "2020-10-23T07:48:04.318123",
"customer": {
"city": "Nürnberg",
"dateOfBirth": "1983-08-16",
"email": "mike#test.com",
"firstName": "Michael",
"netIncome": "FROM_2000_TO_2500",
"number": "123",
"occupation": "EMPLOYEE",
"phone": "+49 171 000 000 00",
"purchasePhase": "EVALUATING",
"street": "Spaldingstr.",
"surName": "mustermann",
"zip": "20097"
},
"request": {
"additionalCosts": 100000,
"brokerageFee": 0.068,
"city": "Stade",
"constructionType": "FOREIGN",
"cost": 500000,
"equity": 200000,
"financingRate": 0.066,
"kfwPromotion": true,
"loan": 400000,
"notaryFee": 0.02,
"realEstateTransferTax": 0.05,
"realEstateType": "APARTMENT",
"realEstateUsage": "RENT",
"zip": "21680"
}
}
]
}
This is my customer Table with customerID as Primary Key:
CREATE TABLE [dbo].[Customer] (
[customerID] INT IDENTITY (1, 1) NOT NULL,
[city] NVARCHAR (50) NULL,
[dateOfBirth] DATE NULL,
[email] NVARCHAR (50) NULL,
[firstName] NVARCHAR (50) NULL,
[netIncome] NVARCHAR (50) NULL,
[number] INT NULL,
[occupation] NVARCHAR (50) NULL,
[phone] NVARCHAR (50) NULL,
[purchasePhase] VARCHAR (50) NULL,
[street] NVARCHAR (50) NULL,
[surName] NVARCHAR (50) NULL,
[zip] INT NULL,
PRIMARY KEY CLUSTERED ([customerID] ASC)
);
The Request Table with requestID as Primary Key:
CREATE TABLE [dbo].[Request] (
[requestID] INT IDENTITY (1, 1) NOT NULL,
[additionalCosts] INT NULL,
[brokerageFee] DECIMAL (18) NULL,
[city] NVARCHAR (50) NULL,
[constructionType] NVARCHAR (50) NULL,
[cost] INT NULL,
[equity] INT NULL,
[financingRate] DECIMAL (18) NULL,
[kfwPromotion] NVARCHAR (50) NULL,
[loan] INT NULL,
[notaryFee] DECIMAL (18) NULL,
[realEstateTransferTax] DECIMAL (18) NULL,
[realEstateType] NVARCHAR (50) NULL,
[realEstateUsage] NVARCHAR (50) NULL,
[zip] INT NULL,
PRIMARY KEY CLUSTERED ([requestID] ASC)
);
the Leads Table:
CREATE TABLE [dbo].[Leads] (
[id] NVARCHAR (50) NOT NULL,
[productID] NVARCHAR (50) NULL,
[created] DATETIME2 (7) NULL,
[customerID] INT NULL,
[requestID] INT NULL,
PRIMARY KEY CLUSTERED ([id] ASC),
CONSTRAINT [FK_Leads_Customer] FOREIGN KEY ([customerID]) REFERENCES [dbo].[Customer] ([customerID]),
CONSTRAINT [FK_Leads_Request] FOREIGN KEY ([requestID]) REFERENCES [dbo].[Request] ([requestID])
);
and my Stored SQL Procedure:
alter Procedure prcInsertCustomer
(#json NVARCHAR(MAX) = '')
AS
BEGIN
DECLARE #LASTcustomerID int = 0
DECLARE #LASTRequestID int = 0
INSERT INTO dbo.Customer
SELECT city, dateOfBirth, email, firstName, netIncome, number, occupation, phone, purchasePhase, street, surName, zip
FROM OPENJSON(#json, '$.Leads')
WITH (
city NVARCHAR(50) '$.customer.city',
dateOfBirth date '$.customer.dateOfBirth',
email NVARCHAR(50) '$.customer.email',
firstName NVARCHAR(50) '$.customer.firstName',
netIncome NVARCHAR(50) '$.customer.netIncome',
number int '$.customer.number',
occupation NVARCHAR(50) '$.customer.occupation',
phone NVARCHAR(50) '$.customer.phone',
purchasePhase NVARCHAR(50) '$.customer.purchasePhase',
street NVARCHAR(50) '$.customer.street',
surName NVARCHAR(50) '$.customer.surName',
zip int '$.customer.zip'
)
SET #LASTcustomerID = IDENT_CURRENT('dbo.customer')
INSERT INTO dbo.Request
SELECT additionalCosts, brokerageFee, city, constructionType, cost, equity, financingRate, kfwPromotion, loan, notaryFee, realEstateTransferTax, realEstateType, realEstateUsage, zip
FROM OPENJSON(#json, '$.Leads')
WITH (
additionalCosts int '$.request.additionalCosts',
brokerageFee decimal(18,0) '$.request.brokerageFee',
city NVARCHAR(50) '$.request.city',
constructionType NVARCHAR(50) '$.request.constructionType',
cost int '$.request.cost',
equity int '$.request.equity',
financingRate decimal(18,0) '$.request.financingRate',
kfwPromotion NVARCHAR(50) '$.request.kfwPromotion',
loan int '$.request.loan',
notaryFee decimal(18,0) '$.request.notaryFee',
realEstateTransferTax decimal(18,0) '$.request.realEstateTransferTax',
realEstateType NVARCHAR(50) '$.request.realEstateType',
realEstateUsage NVARCHAR(50) '$.request.realEstateUsage',
zip int '$.request.zip'
)
SET #LASTRequestID = IDENT_CURRENT('dbo.Request')
INSERT INTO dbo.Leads
SELECT id, productId, created, #LASTcustomerID, #LASTRequestID
FROM OPENJSON(#json, '$.Leads')
WITH (
id NVARCHAR(50) '$.id',
productId NVARCHAR(50) '$.productId',
created datetime2(7) '$.created'
)
END
Now every time I run my stored procedure I have the Same IDs in both Leads:
And I need to proceed all Lead Items from JSON in ONE run.

SQL Server Parse JSON Object to Rows

Thanks in advance for any help. This is killing me! :-)
I have a JSON string that has an object collection nested within it that I need to get a standard SQL result set from. Here is a sample string of the JSON I am working with:
{
"ST": {
"TransactionSetIdentifierCode_01": "835",
"TransactionSetControlNumber_02": "1740",
"ImplementationConventionPreference_03": null
},
"BPR_FinancialInformation": {
"TransactionHandlingCode_01": "I",
"TotalPremiumPaymentAmount_02": "45.75",
"CreditorDebitFlagCode_03": "C",
"PaymentMethodCode_04": "ACH",
"PaymentFormatCode_05": "CCP",
"DepositoryFinancialInstitutionDFIIdentificationNumberQualifier_06": "01",
"OriginatingDepositoryFinancialInstitutionDFIIdentifier_07": "111",
"AccountNumberQualifier_08": "DA",
"SenderBankAccountNumber_09": "33",
"PayerIdentifier_10": "1234567890",
"OriginatingCompanySupplementalCode_11": null,
"DepositoryFinancialInstitutionDFIIdentificationNumberQualifier_12": "01",
"ReceivingDepositoryFinancialInstitutionDFIIdentifier_13": "111",
"AccountNumberQualifier_14": "DA",
"ReceiverBankAccountNumber_15": "22",
"CheckIssueorEFTEffectiveDate_16": "20100101",
"BusinessFunctionCode_17": null,
"DFIIDNumberQualifier_18": null,
"DFIIdentificationNumber_19": null,
"AccountNumberQualifier_20": null,
"AccountNumber_21": null
},
"TRN_ReassociationTraceNumber": {
"TraceTypeCode_01": "1",
"CurrentTransactionTraceNumber_02": "10100000000",
"OriginatingCompanyIdentifier_03": "1000000000",
"ReferenceIdentification_04": null
},
"CUR_ForeignCurrencyInformation": null,
"AllREF": {
"REF_ReceiverIdentification": {
"ReferenceIdentificationQualifier_01": "EV",
"MemberGrouporPolicyNumber_02": "ETIN",
"Description_03": null,
"ReferenceIdentifier_04": null
},
"REF_VersionIdentification": null
},
"DTM_ProductionDate": {
"DateTimeQualifier_01": "405",
"Date_02": "20100101",
"Time_03": null,
"TimeCode_04": null,
"DateTimePeriodFormatQualifier_05": null,
"DateTimePeriod_06": null
},
"AllN1": {
"Loop1000A": {
"N1_PayerIdentification": {
"EntityIdentifierCode_01": "PR",
"PremiumPayerName_02": "NYSDOH",
"IdentificationCodeQualifier_03": null,
"IntermediaryBankIdentifier_04": null,
"EntityRelationshipCode_05": null,
"EntityIdentifierCode_06": null
},
"N3_PayerAddress": {
"ResponseContactAddressLine_01": "OFFICE OF HEALTH INSURANCE PROGRAMS",
"ResponseContactAddressLine_02": "CORNING TOWER, EMPIRE STATE PLAZA"
},
"N4_PayerCity_State_ZIPCode": {
"AdditionalPatientInformationContactCityName_01": "ALBANY",
"AdditionalPatientInformationContactStateCode_02": "NY",
"AdditionalPatientInformationContactPostalZoneorZIPCode_03": "122370080",
"CountryCode_04": null,
"LocationQualifier_05": null,
"LocationIdentifier_06": null,
"CountrySubdivisionCode_07": null
},
"REF_AdditionalPayerIdentification": null,
"AllPER": {
"PER_PayerBusinessContactInformation": null,
"PER_PayerTechnicalContactInformation": [
{
"ContactFunctionCode_01": "BL",
"ResponseContactName_02": "PROVIDER SERVICES",
"CommunicationNumberQualifier_03": "TE",
"ResponseContactCommunicationNumber_04": "8003439000",
"CommunicationNumberQualifier_05": "UR",
"ResponseContactCommunicationNumber_06": "www.emedny.org",
"CommunicationNumberQualifier_07": null,
"ResponseContactCommunicationNumber_08": null,
"ContactInquiryReference_09": null
}
],
"PER_PayerWEBSite": null
}
},
"Loop1000B": {
"N1_PayeeIdentification": {
"EntityIdentifierCode_01": "PE",
"PremiumPayerName_02": "MAJOR MEDICAL PROVIDER",
"IdentificationCodeQualifier_03": "XX",
"IntermediaryBankIdentifier_04": "9999999995",
"EntityRelationshipCode_05": null,
"EntityIdentifierCode_06": null
},
"N3_PayeeAddress": null,
"N4_PayeeCity_State_ZIPCode": null,
"REF_PayeeAdditionalIdentification": [
{
"ReferenceIdentificationQualifier_01": "TJ",
"MemberGrouporPolicyNumber_02": "000000000",
"Description_03": null,
"ReferenceIdentifier_04": null
}
],
"RDM_RemittanceDeliveryMethod": null
}
},
"Loop2000": [
{
"LX_HeaderNumber": {
"AssignedNumber_01": "1"
},
"TS3_ProviderSummaryInformation": null,
"TS2_ProviderSupplementalSummaryInformation": null,
"Loop2100": [
{
"CLP_ClaimPaymentInformation": {
"PatientControlNumber_01": "PATIENT ACCOUNT NUMBER",
"ClaimStatusCode_02": "1",
"TotalClaimChargeAmount_03": "34.25",
"ClaimPaymentAmount_04": "34.25",
"PatientResponsibilityAmount_05": null,
"ClaimFilingIndicatorCode_06": "MC",
"PayerClaimControlNumber_07": "1000210000000030",
"FacilityTypeCode_08": "11",
"ClaimFrequencyCode_09": null,
"PatientStatusCode_10": null,
"DiagnosisRelatedGroupDRGCode_11": null,
"DiagnosisRelatedGroupDRGWeight_12": null,
"DischargeFraction_13": null,
"YesNoConditionorResponseCode_14": null
},
"CAS_ClaimsAdjustment": null,
"AllNM1": {
"NM1_PatientName": {
"EntityIdentifierCode_01": "QC",
"EntityTypeQualifier_02": "1",
"ResponseContactLastorOrganizationName_03": "SUBMITTED LAST",
"ResponseContactFirstName_04": "SUBMITTED FIRST",
"ResponseContactMiddleName_05": null,
"NamePrefix_06": null,
"ResponseContactNameSuffix_07": null,
"IdentificationCodeQualifier_08": "MI",
"ResponseContactIdentifier_09": "LL99999L",
"EntityRelationshipCode_10": null,
"EntityIdentifierCode_11": null,
"NameLastorOrganizationName_12": null
},
"NM1_InsuredName": null,
"NM1_CorrectedPatient_InsuredName": {
"EntityIdentifierCode_01": "74",
"EntityTypeQualifier_02": "1",
"ResponseContactLastorOrganizationName_03": "CORRECTED LAST",
"ResponseContactFirstName_04": "CORRECTED FIRST",
"ResponseContactMiddleName_05": null,
"NamePrefix_06": null,
"ResponseContactNameSuffix_07": null,
"IdentificationCodeQualifier_08": null,
"ResponseContactIdentifier_09": null,
"EntityRelationshipCode_10": null,
"EntityIdentifierCode_11": null,
"NameLastorOrganizationName_12": null
},
"NM1_ServiceProviderName": null,
"NM1_CrossoverCarrierName": null,
"NM1_CorrectedPriorityPayerName": null,
"NM1_OtherSubscriberName": null
},
"MIA_InpatientAdjudicationInformation": null,
"MOA_OutpatientAdjudicationInformation": null,
"AllREF": {
"REF_OtherClaimRelatedIdentification": [
{
"ReferenceIdentificationQualifier_01": "EA",
"MemberGrouporPolicyNumber_02": "PATIENT ACCOUNT NUMBER",
"Description_03": null,
"ReferenceIdentifier_04": null
}
],
"REF_RenderingProviderIdentification": null
},
"AllDTM": {
"DTM_StatementFromorToDate": [
{
"DateTimeQualifier_01": "232",
"Date_02": "20100101",
"Time_03": null,
"TimeCode_04": null,
"DateTimePeriodFormatQualifier_05": null,
"DateTimePeriod_06": null
},
{
"DateTimeQualifier_01": "233",
"Date_02": "20100101",
"Time_03": null,
"TimeCode_04": null,
"DateTimePeriodFormatQualifier_05": null,
"DateTimePeriod_06": null
}
],
"DTM_CoverageExpirationDate": null,
"DTM_ClaimReceivedDate": null
},
"PER_ClaimContactInformation": null,
"AMT_ClaimSupplementalInformation": [
{
"AmountQualifierCode_01": "AU",
"TotalClaimChargeAmount_02": "34.25",
"CreditDebitFlagCode_03": null
}
],
"QTY_ClaimSupplementalInformationQuantity": null,
"Loop2110": null
},
{
"CLP_ClaimPaymentInformation": {
"PatientControlNumber_01": "PATIENT ACCOUNT NUMBER",
"ClaimStatusCode_02": "2",
"TotalClaimChargeAmount_03": "34",
"ClaimPaymentAmount_04": "0",
"PatientResponsibilityAmount_05": null,
"ClaimFilingIndicatorCode_06": "MC",
"PayerClaimControlNumber_07": "1000220000000020",
"FacilityTypeCode_08": "11",
"ClaimFrequencyCode_09": null,
"PatientStatusCode_10": null,
"DiagnosisRelatedGroupDRGCode_11": null,
"DiagnosisRelatedGroupDRGWeight_12": null,
"DischargeFraction_13": null,
"YesNoConditionorResponseCode_14": null
},
"CAS_ClaimsAdjustment": null,
"AllNM1": {
"NM1_PatientName": {
"EntityIdentifierCode_01": "QC",
"EntityTypeQualifier_02": "1",
"ResponseContactLastorOrganizationName_03": "SUBMITTED LAST",
"ResponseContactFirstName_04": "SUBMITTED FIRST",
"ResponseContactMiddleName_05": null,
"NamePrefix_06": null,
"ResponseContactNameSuffix_07": null,
"IdentificationCodeQualifier_08": "MI",
"ResponseContactIdentifier_09": "LL88888L",
"EntityRelationshipCode_10": null,
"EntityIdentifierCode_11": null,
"NameLastorOrganizationName_12": null
},
"NM1_InsuredName": null,
"NM1_CorrectedPatient_InsuredName": {
"EntityIdentifierCode_01": "74",
"EntityTypeQualifier_02": "1",
"ResponseContactLastorOrganizationName_03": "CORRECTED LAST",
"ResponseContactFirstName_04": "CORRECTED FIRST",
"ResponseContactMiddleName_05": null,
"NamePrefix_06": null,
"ResponseContactNameSuffix_07": null,
"IdentificationCodeQualifier_08": null,
"ResponseContactIdentifier_09": null,
"EntityRelationshipCode_10": null,
"EntityIdentifierCode_11": null,
"NameLastorOrganizationName_12": null
},
"NM1_ServiceProviderName": null,
"NM1_CrossoverCarrierName": null,
"NM1_CorrectedPriorityPayerName": null,
"NM1_OtherSubscriberName": null
},
"MIA_InpatientAdjudicationInformation": null,
"MOA_OutpatientAdjudicationInformation": null,
"AllREF": {
"REF_OtherClaimRelatedIdentification": [
{
"ReferenceIdentificationQualifier_01": "EA",
"MemberGrouporPolicyNumber_02": "PATIENT ACCOUNT NUMBER",
"Description_03": null,
"ReferenceIdentifier_04": null
}
],
"REF_RenderingProviderIdentification": null
},
"AllDTM": {
"DTM_StatementFromorToDate": [
{
"DateTimeQualifier_01": "232",
"Date_02": "20100101",
"Time_03": null,
"TimeCode_04": null,
"DateTimePeriodFormatQualifier_05": null,
"DateTimePeriod_06": null
},
{
"DateTimeQualifier_01": "233",
"Date_02": "20100101",
"Time_03": null,
"TimeCode_04": null,
"DateTimePeriodFormatQualifier_05": null,
"DateTimePeriod_06": null
}
],
"DTM_CoverageExpirationDate": null,
"DTM_ClaimReceivedDate": null
},
"PER_ClaimContactInformation": null,
"AMT_ClaimSupplementalInformation": null,
"QTY_ClaimSupplementalInformationQuantity": null,
"Loop2110": null
},
{
"CLP_ClaimPaymentInformation": {
"PatientControlNumber_01": "PATIENT ACCOUNT NUMBER",
"ClaimStatusCode_02": "2",
"TotalClaimChargeAmount_03": "34.25",
"ClaimPaymentAmount_04": "11.5",
"PatientResponsibilityAmount_05": null,
"ClaimFilingIndicatorCode_06": "MC",
"PayerClaimControlNumber_07": "1000230000000020",
"FacilityTypeCode_08": "11",
"ClaimFrequencyCode_09": null,
"PatientStatusCode_10": null,
"DiagnosisRelatedGroupDRGCode_11": null,
"DiagnosisRelatedGroupDRGWeight_12": null,
"DischargeFraction_13": null,
"YesNoConditionorResponseCode_14": null
},
"CAS_ClaimsAdjustment": null,
"AllNM1": {
"NM1_PatientName": {
"EntityIdentifierCode_01": "QC",
"EntityTypeQualifier_02": "1",
"ResponseContactLastorOrganizationName_03": "SUBMITTED LAST",
"ResponseContactFirstName_04": "SUBMITTED FIRST",
"ResponseContactMiddleName_05": null,
"NamePrefix_06": null,
"ResponseContactNameSuffix_07": null,
"IdentificationCodeQualifier_08": "MI",
"ResponseContactIdentifier_09": "LL77777L",
"EntityRelationshipCode_10": null,
"EntityIdentifierCode_11": null,
"NameLastorOrganizationName_12": null
},
"NM1_InsuredName": null,
"NM1_CorrectedPatient_InsuredName": {
"EntityIdentifierCode_01": "74",
"EntityTypeQualifier_02": "1",
"ResponseContactLastorOrganizationName_03": "CORRECTED LAST",
"ResponseContactFirstName_04": "CORRECTED FIRST",
"ResponseContactMiddleName_05": null,
"NamePrefix_06": null,
"ResponseContactNameSuffix_07": null,
"IdentificationCodeQualifier_08": null,
"ResponseContactIdentifier_09": null,
"EntityRelationshipCode_10": null,
"EntityIdentifierCode_11": null,
"NameLastorOrganizationName_12": null
},
"NM1_ServiceProviderName": null,
"NM1_CrossoverCarrierName": null,
"NM1_CorrectedPriorityPayerName": null,
"NM1_OtherSubscriberName": null
},
"MIA_InpatientAdjudicationInformation": null,
"MOA_OutpatientAdjudicationInformation": null,
"AllREF": {
"REF_OtherClaimRelatedIdentification": [
{
"ReferenceIdentificationQualifier_01": "EA",
"MemberGrouporPolicyNumber_02": "PATIENT ACCOUNT NUMBER",
"Description_03": null,
"ReferenceIdentifier_04": null
}
],
"REF_RenderingProviderIdentification": null
},
"AllDTM": {
"DTM_StatementFromorToDate": [
{
"DateTimeQualifier_01": "232",
"Date_02": "20100101",
"Time_03": null,
"TimeCode_04": null,
"DateTimePeriodFormatQualifier_05": null,
"DateTimePeriod_06": null
},
{
"DateTimeQualifier_01": "233",
"Date_02": "20100101",
"Time_03": null,
"TimeCode_04": null,
"DateTimePeriodFormatQualifier_05": null,
"DateTimePeriod_06": null
}
],
"DTM_CoverageExpirationDate": null,
"DTM_ClaimReceivedDate": null
},
"PER_ClaimContactInformation": null,
"AMT_ClaimSupplementalInformation": [
{
"AmountQualifierCode_01": "AU",
"TotalClaimChargeAmount_02": "11.5",
"CreditDebitFlagCode_03": null
}
],
"QTY_ClaimSupplementalInformationQuantity": null,
"Loop2110": null
}
]
}
],
"PLB_ProviderAdjustment": null,
"SE": {
"NumberofIncludedSegments_01": "65",
"TransactionSetControlNumber_02": "1740"
},
"ErrorContext": {
"Name": "835",
"ControlNumber": "1740",
"Edition": "005010",
"Release": "X221A1",
"Index": 2,
"ValidatedSegmentsCount": 0,
"Codes": [],
"Errors": [
{
"Name": "SVC",
"Position": 20,
"LoopId": null,
"Value": "SVC*HC:V2020:RB*6*6**1",
"Codes": [
4
],
"Errors": [],
"Message": "Segment SVC*HC:V2020:RB*6 is not allowed in this position. Only the following segments can appear: AMT, QTY, SVC, CLP, LX, PLB, SE"
}
],
"HasErrors": true,
"Message": null
}
}
This string can be pasted into an online JSON parser to visualize the hierarchy more easily (like http://json.parser.online.fr/).
What I am trying to do is use the SQL Server OPENJSON function to get a result set of the 3 sample claims in this JSON string. The claims are nested in $.Loop2000.Loop2100, and the result I am trying to get is:
Patient Account Number ClaimStatusCode TotalClaimChargeAmount
------------------------------------------------------------------------
Patient Account Number 1 34.25
Patient Account Number 2 34.00
Patient Account Number 3 34.00
I can't seem to get the path right in the OPENJSON function to turn this into a result set with 3 rows. I am trying to use something like:
SELECT * FROM OPENJSON(#sJSON, N'$.Loop2000.Loop2100')
WITH (
PatientControlNumber_01 nvarchar(100) '$.CLP_ClaimPaymentInformation.PatientControlNumber_01'
)
Any help would be much appreciated.
One method you could use is a few nested OPNEJSON calls:
SELECT CPI.*
FROM OPENJSON(#JSON, N'$.Loop2000')
WITH (Loop2100 nvarchar(MAX) AS JSON) L2000
CROSS APPLY OPENJSON(L2000.Loop2100)
WITH(CLP_ClaimPaymentInformation nvarchar(MAX) AS JSON) L2100
CROSS APPLY OPENJSON(L2100.CLP_ClaimPaymentInformation)
WITH (PatientControlNumber varchar(100) '$.PatientControlNumber_01',
ClaimStatusCode int '$.ClaimStatusCode_02',
TotalClaimChargeAmount decimal(12,2) '$.TotalClaimChargeAmount_03') CPI;

How to update a nested record to a static value

I have nested data and want to update a value of a key of an array which is actually in array format user_properties['first_open_time']['int_value']. I want to change this value to a static value -1582243200000 ie.-. Sample structure of the data is as below:
[
{
"user_properties": [
{
"key": "ga_session_id",
"value": {
"string_value": null,
"int_value": "1582306435",
"float_value": null,
"double_value": null,
"set_timestamp_micros": "1582306435527000"
}
},
{
"key": "ga_session_number",
"value": {
"string_value": null,
"int_value": "1",
"float_value": null,
"double_value": null,
"set_timestamp_micros": "1582306435527000"
}
},
{
"key": "first_open_time",
"value": {
"string_value": null,
"int_value": "1582308000000",
"float_value": null,
"double_value": null,
"set_timestamp_micros": "1582306432489000"
}
}
]
}
]
You basically need to reconstruct the struct, changing what you want to change in the process:
-- CREATE TABLE `temp.firebase_sample`
-- AS (
-- SELECT * FROM `bingo-blast-174dd.analytics_151321511.events_20200225`
-- );
UPDATE `temp.firebase_sample` a
SET user_properties = (
SELECT
ARRAY_AGG(STRUCT(key,
STRUCT(value.string_value,
IF(key='first_open_time', 1582243200000, value.int_value),
value.float_value,
value.double_value,
value.set_timestamp_micros)))
FROM UNNEST(a.user_properties) x)
WHERE TRUE

How to insert STRUCT values in Google Big Query?

We have standart analytics table in GoogleBigQuery:
We need to insert new data, with:
event_date,
event_timestamp,
event_name,
event_params.key.value,
event_params.value.string_value,
device.advertising_id
And I can't understand, how i can do it, with "event_params.key.value, event_params.value.string_value, device.advertising_id".
Can you help me make a request?
Somethink like this
INSERT
INTO `table`.`analytics_183424923.events_intraday_20191120`
(
`event_date`,
`event_timestamp`,
`event_name`,
`device.advertising_id`
)
VALUES
(
'20191120',
1574212435206765,
'custom_event',
'deviceId'
);
Here our table in JSON.
[
{
"event_date": "20191120",
"event_timestamp": "1574236440549659",
"event_name": "SHOW_INTERSTITIAL",
"event_params": [
{
"key": "has",
"value": {
"string_value": "0",
"int_value": null,
"float_value": null,
"double_value": null
}
},
{
"key": "firebase_event_origin",
"value": {
"string_value": "app",
"int_value": null,
"float_value": null,
"double_value": null
}
}
],
"event_previous_timestamp": "1574236295986010",
"event_value_in_usd": null,
"event_bundle_sequence_id": "19",
"event_server_timestamp_offset": "6519649",
"user_id": null,
"user_pseudo_id": "1d28ad03ef14b6991cbbcf5c69c5db3f",
"user_properties": [
{
"key": "first_open_time",
"value": {
"string_value": null,
"int_value": "1538305200000",
"float_value": null,
"double_value": null,
"set_timestamp_micros": "1538302277504649"
}
}
],
"device": {
"category": "mobile",
"advertising_id": "8ae303e4-b94b-4599-929c-c8ae3c418ed7",
}
]
INSERT
INTO `table`.`analytics_183424923.events_intraday_20191120`
(
`event_date`,
`event_timestamp`,
`event_name`,
`device`
)
VALUES
(
'20191120',
1574212435206765,
'custom_event',
struct<category string, advertising_id string>('mobile', 'deviceId')
);
A simpler form would work in your case, but sometimes your have to specify the full field list of a struct as above.
Simpler one:
...
VALUES
(
'20191120',
1574212435206765,
'custom_event',
('mobile', 'deviceId')
);

How to create a tree[forest tree model] from the JSON...?

Below is my JSON. I'm trying to create a tree out of this,
I tried with the following snippet:
require(["dijit/Tree", "dojo/data/ItemFileReadStore", "dijit/tree/ForestStoreModel", "dojo/domReady!"],
function(Tree, ItemFileReadStore, ForestStoreModel){
var store = new ItemFileReadStore({
url: "/om/web/em/tree.json"
});
var treeModel = new ForestStoreModel({
store: store,
query: {id: 'aid'},
rootId: "PSS-32",
rootLabel: "P",
childrenAttrs: ['eqList']
});
var myTree = new Tree({
model: treeModel
}, "treeOne");
myTree.startup();
});
But this is giving me error loading PSS010010026024 children and message: "Cannot read property 'length' of undefined errors,what should be specified in the rootID,rootLabel and childrenAttrs?
[
{
"responseStatus": null,
"entityType": "NODE",
"aid": "p",
"id": "p",
"hsa": null,
"eqList":[ {
"responseStatus": null,
"EId": "5",
"EGroupId": "1006",
"aid": "p",
"additionalInfo": null,
"eqList": [
{
"responseStatus": null,
"EId": null,
"EGroupId": null,
"aid": null,
"additionalInfo": null,
"eqList": null,
"shelfType": null,
"isEqAvailable": null,
"id": null,
"entityType": null,
"hsa": null,
"Elist": null
}
],
"shelfType": null,
"isEqAvailable": null,
"id": "p/p",
"entityType": "E",
"hsa": "-",
"Elist": null
{
"responseStatus": null,
"EId": "5",
"EGroupId": "1006",
"aid": "p#OCS",
"EType": "1830pss-ocs",
"ERelease": "7.0",
"additionalInfo": null,
"eqList": [
{
"responseStatus": null,
"EId": null,
"EGroupId": null,
"aid": null,
"EType": null,
"ERelease": null,
"additionalInfo": null,
"eqList": null,
"shelfType": null,
"isEqAvailable": null,
"id": null,
"entityType": null,
"hsa": null,
"Elist": null
}
],
"shelfType": null,
"isEqAvailable": null,
"id": "p/p#OCS",
"entityType": "E",
"hsa": "-",
"Elist": null
}
]
}
]
The rootID attribute is what ID you want to give the root item that will be created (so that you can query for it later or check if your tree is at the top level). The rootLabel is what you want the label of the root attribute to be. The childrenAttrs is how you tell the Tree where a specific node's children are.
I'm not sure what you're trying to do in your code though since your data doesn't seem to have PSS010010026024 in it but I would recommend checking out the API documentation for the ForestTreeModel here: http://dojotoolkit.org/api/?qs=1.9/dijit/tree/ForestStoreModel