Liquibase and H2 problem with not existing table - database

I have a problem with liquibase and H2 database. I wanted to add some testing to my liquibase schema on push to github via github workflow. So I have decided to make a SpringBoot profile with H2 to make it work. And almost everything works. In two cases, I add constraints via sql and it gives me an exception telling that this table does not exist. When I comment those sql statements, then the whole thing works like a charm.
So, here is my yaml file for test profile:
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:task_schema;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;IGNORECASE=TRUE;INIT=CREATE SCHEMA IF NOT EXISTS TASK_SCHEMA
username: sa
password:
initialization-mode: always
liquibase:
default-schema: task_schema
drop-first: true
change-log: classpath:/database/changelogs/changelog-master.xml
autoconfigure:
exclude: org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
jpa:
database-platform: org.hibernate.dialect.H2Dialect
openInView: false
show_sql: true
generate-ddl: true
hibernate:
ddl-auto: create
properties:
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true
changelog with interesting changes:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
<include file="create-client-sequence.xml" relativeToChangelogFile="true"/>
<include file="create-client-table.xml" relativeToChangelogFile="true"/>
<include file="add-client-name-constraint.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>
create-client-table.xml:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
<changeSet author="liquibase" id="create-client-table">
<createTable tableName="CLIENT">
<column name="ID" type="${long.type}">
<constraints nullable="false"/>
</column>
<column name="UUID" type="UUID">
<constraints nullable="false"/>
</column>
<column name="FIRST_NAME" type="VARCHAR2(32 ${char.unit})">
<constraints nullable="true"/>
</column>
<column name="LAST_NAME" type="VARCHAR2(32 ${char.unit})">
<constraints nullable="true"/>
</column>
<column name="COMPANY_NAME" type="VARCHAR2(32 ${char.unit})">
<constraints nullable="true"/>
</column>
<column name="EMAIL" type="VARCHAR2(50 ${char.unit})"/>
<column name="NOTE" type="VARCHAR2(1000 ${char.unit})"/>
<column name="TELEPHONE" type="VARCHAR2(20 ${char.unit})"/>
<column name="PROJECTS_VALUE" type="${big_decimal.type}" defaultValueNumeric="0.0">
<constraints nullable="false"/>
</column>
<column name="CLIENT_TYPE" type="VARCHAR2(20 ${char.unit})">
<constraints nullable="false"/>
</column>
<column name="POST_CODE" type="VARCHAR2(6 ${char.unit})"/>
<column name="CITY" type="VARCHAR2(30 ${char.unit})"/>
<column name="STREET" type="VARCHAR2(30 ${char.unit})"/>
<column name="HOUSE_NUMBER" type="VARCHAR2(5 ${char.unit})"/>
<column name="FLAT_NUMBER" type="VARCHAR2(5 ${char.unit})"/>
</createTable>
<addPrimaryKey tableName="CLIENT" columnNames="ID" constraintName="PK_CLIENT"/>
</changeSet>
</databaseChangeLog>
and add-client-name-constraint.xml:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
<changeSet author="liquibase" id="add-client-name-constraint">
<sql>
alter table CLIENT add constraint NAME_NOT_NULL
check
(
((CLIENT_TYPE = 'PRIVATE') and ((FIRST_NAME is NOT NULL) AND (LAST_NAME is NOT NULL))) or
((CLIENT_TYPE = 'CORPORATE') and (COMPANY_NAME is NOT NULL))
);
</sql>
</changeSet>
</databaseChangeLog>
and some part of stack trace (sorry for Polish there):
2021-06-07 20:49:29.122 INFO 1607585 --- [ main] l.e.j.JdbcExecutor : CREATE TABLE TASK_SCHEMA.CLIENT (ID BIGINT NOT NULL, UUID UUID NOT NULL, FIRST_NAME VARCHAR(32), LAST_NAME VARCHAR(32), COMPANY_NAME VARCHAR(32), EMAIL VARCHAR(50), NOTE VARCHAR(1000), TELEPHONE VARCHAR(20), PROJECTS_VALUE DECIMAL(19, 6) DEFAULT 0 NOT NULL, CLIENT_TYPE VARCHAR(20) NOT NULL, POST_CODE VARCHAR(6), CITY VARCHAR(30), STREET VARCHAR(30), HOUSE_NUMBER VARCHAR(5), FLAT_NUMBER VARCHAR(5))
2021-06-07 20:49:29.123 INFO 1607585 --- [ main] l.c.ChangeSet : Table CLIENT created
2021-06-07 20:49:29.123 INFO 1607585 --- [ main] l.e.j.JdbcExecutor : ALTER TABLE TASK_SCHEMA.CLIENT ADD CONSTRAINT PK_CLIENT PRIMARY KEY (ID)
2021-06-07 20:49:29.124 INFO 1607585 --- [ main] l.c.ChangeSet : Primary key added to CLIENT (ID)
2021-06-07 20:49:29.124 INFO 1607585 --- [ main] l.c.ChangeSet : ChangeSet classpath:/database/changelogs/v1.0.0/client/create-client-table.xml::create-client-table::liquibase ran successfully in 3ms
2021-06-07 20:49:29.124 INFO 1607585 --- [ main] l.e.j.JdbcExecutor : INSERT INTO TASK_SCHEMA.DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, MD5SUM, DESCRIPTION, COMMENTS, EXECTYPE, CONTEXTS, LABELS, LIQUIBASE, DEPLOYMENT_ID) VALUES ('create-client-table', 'liquibase', 'classpath:/database/changelogs/v1.0.0/client/create-client-table.xml', NOW(), 4, '8:9f420f03a34211b142d310064019080e', 'createTable tableName=CLIENT; addPrimaryKey constraintName=PK_CLIENT, tableName=CLIENT', '', 'EXECUTED', NULL, NULL, '3.10.1', '3091768994')
2021-06-07 20:49:29.129 INFO 1607585 --- [ main] l.e.j.JdbcExecutor : alter table CLIENT add constraint NAME_NOT_NULL
check
(
((CLIENT_TYPE = 'PRIVATE') and ((FIRST_NAME is NOT NULL) AND (LAST_NAME is NOT NULL))) or
((CLIENT_TYPE = 'CORPORATE') and (COMPANY_NAME is NOT NULL))
)
2021-06-07 20:49:29.130 ERROR 1607585 --- [ main] l.c.ChangeSet : Change Set classpath:/database/changelogs/v1.0.0/client/add-client-name-constraint.xml::add-client-name-constraint::liquibase failed. Error: Tabela "CLIENT" nie istnieje
Table "CLIENT" not found; SQL statement:
alter table CLIENT add constraint NAME_NOT_NULL
check
(
((CLIENT_TYPE = 'PRIVATE') and ((FIRST_NAME is NOT NULL) AND (LAST_NAME is NOT NULL))) or
((CLIENT_TYPE = 'CORPORATE') and (COMPANY_NAME is NOT NULL))
) [42102-200] [Failed SQL: (42102) alter table CLIENT add constraint NAME_NOT_NULL
check
(
((CLIENT_TYPE = 'PRIVATE') and ((FIRST_NAME is NOT NULL) AND (LAST_NAME is NOT NULL))) or
((CLIENT_TYPE = 'CORPORATE') and (COMPANY_NAME is NOT NULL))
)]
2021-06-07 20:49:29.131 INFO 1607585 --- [ main] l.l.StandardLockService : Successfully released change log lock
2021-06-07 20:49:29.132 WARN 1607585 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:/database/changelogs/v1.0.0/client/add-client-name-constrain.xml::add-client-name-constraint::liquibase:
Reason: liquibase.exception.DatabaseException: Tabela "CLIENT" nie istnieje
Table "CLIENT" not found; SQL statement:
alter table CLIENT add constraint NAME_NOT_NULL
check
(
((CLIENT_TYPE = 'PRIVATE') and ((FIRST_NAME is NOT NULL) AND (LAST_NAME is NOT NULL))) or
((CLIENT_TYPE = 'CORPORATE') and (COMPANY_NAME is NOT NULL))
) [42102-200] [Failed SQL: (42102) alter table CLIENT add constraint NAME_NOT_NULL
check
(
((CLIENT_TYPE = 'PRIVATE') and ((FIRST_NAME is NOT NULL) AND (LAST_NAME is NOT NULL))) or
((CLIENT_TYPE = 'CORPORATE') and (COMPANY_NAME is NOT NULL))
)]
2021-06-07 20:49:29.133 INFO 1607585 --- [ main] o.s.s.c.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2021-06-07 20:49:29.133 INFO 1607585 --- [ main] c.z.h.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-06-07 20:49:29.136 INFO 1607585 --- [ main] c.z.h.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-06-07 20:49:29.142 INFO 1607585 --- [ main] ConditionEvaluationReportLoggingListener :
I will appreciate any help.
EDIT:
Solved. For h2 SQL I have added schema name before table name and it works. The strange part of it is, that if I run H2 in console, it does not require that. So now, the file looks like this:
and add-client-name-constraint.xml:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
<changeSet author="liquibase" id="add-client-name-constraint">
<sql dbms="postgresql">
alter table CLIENT add constraint NAME_NOT_NULL
check
(
((CLIENT_TYPE = 'PRIVATE') and ((FIRST_NAME is NOT NULL) AND (LAST_NAME is NOT NULL))) or
((CLIENT_TYPE = 'CORPORATE') and (COMPANY_NAME is NOT NULL))
);
</sql>
<sql dbms="h2">
alter table TASK_SCHEMA.CLIENT add constraint NAME_NOT_NULL
check
(
((CLIENT_TYPE = 'PRIVATE') and ((FIRST_NAME is NOT NULL) AND (LAST_NAME is NOT NULL))) or
((CLIENT_TYPE = 'CORPORATE') and (COMPANY_NAME is NOT NULL))
);
</sql>
</changeSet>
</databaseChangeLog>

Related

Read XML on SQL Server : Select custom attribute

I'm trying to read an XML, it works pretty well on the whole except for the attribute named :
<custom-attribute attribute-id="loyaltyNumber">1234567890</custom-attribute>
which I am trying to get the value "1234567890"
Here is the test code:
DECLARE #XML XML = '<customers>
<customer customer-no="00000001">
<credentials>
<login>test#email.com</login>
</credentials>
<profile>
<preferred-locale>fr_BE</preferred-locale>
<custom-attributes>
<custom-attribute attribute-id="ServiceId">1</custom-attribute>
<custom-attribute attribute-id="loyaltyNumber">1234567890</custom-attribute>
</custom-attributes>
</profile>
<note/>
</customer>
<customer customer-no="00000002">
<credentials>
<login>test2#email.com</login>
</credentials>
<profile>
<preferred-locale>fr_FR</preferred-locale>
<custom-attributes>
<custom-attribute attribute-id="loyaltyNumber">1234567890</custom-attribute>
</custom-attributes>
</profile>
<note/>
</customer>
</customers>'
SELECT
CustomerNo = Events.value('#customer-no', 'int'),
--EventType = Events.value('#Type', 'varchar(20)'),
CustomerLogin =Events.value('(credentials/login)[1]', 'varchar(60)'),
CustomerLocal =Events.value('(profile/preferred-locale)[1]', 'varchar(60)'),
EventKind =Events.value('(profile/custom-attributes/custom-attribute)[2]', 'varchar(60)')
FROM
#XML.nodes('/customers/customer') AS XTbl(Events)
The current result is:
CustomerNo
CustomerLogin
CustomerLocal
EventKind
1
test#email.com
fr_BE
1234567890
2
test2#email.com
fr_FR
NULL
And it's logical since custom-attributes are optional, so you can't access them with the index.
So I'm looking for a way to access them by name: attribute-id="loyaltyNumber"
Thanks,
..filter the path to the attribute which has attribute-id = “loyaltyNumber”
EventKind =Events.value('(profile/custom-attributes/custom-attribute[#attribute-id="loyaltyNumber"])[1]', 'varchar(60)')
You can just add the attribute-id of the custom attribute to your query:
DECLARE #XML XML = '<customers>
<customer customer-no="00000001">
<credentials>
<login>test#email.com</login>
</credentials>
<profile>
<preferred-locale>fr_BE</preferred-locale>
<custom-attributes>
<custom-attribute attribute-id="ServiceId">1</custom-attribute>
<custom-attribute attribute-id="loyaltyNumber">1234567890</custom-attribute>
</custom-attributes>
</profile>
<note/>
</customer>
<customer customer-no="00000002">
<credentials>
<login>test2#email.com</login>
</credentials>
<profile>
<preferred-locale>fr_FR</preferred-locale>
<custom-attributes>
<custom-attribute attribute-id="loyaltyNumber">1234567777</custom-attribute>
</custom-attributes>
</profile>
<note/>
</customer>
</customers>'
SELECT
CustomerNo = Events.value('#customer-no', 'int'),
--EventType = Events.value('#Type', 'varchar(20)'),
CustomerLogin =Events.value('(credentials/login)[1]', 'varchar(60)'),
CustomerLocal =Events.value('(profile/preferred-locale)[1]', 'varchar(60)'),
EventKind =Events.value('(profile/custom-attributes/custom-attribute[#attribute-id = "loyaltyNumber"])[1]', 'varchar(60)')
FROM
#XML.nodes('/customers/customer') AS XTbl(Events)

SQL XML - Create a XML file from SQL Server for an invoice including invoice positions in one XML file

I create my xml file in this way (I do not show all output fields because there are very many fields):
DECLARE #ID_Rechnung int = 8;
WITH XMLNAMESPACES (
'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as ext,
'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc,
'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac,
'http://uri.etsi.org/01903/v1.3.2#' as xades,
'http://www.w3.org/2001/XMLSchema-instance' as xsi,
'http://www.w3.org/2000/09/xmldsig#' as ds
)
SELECT
#XMLData = xmldat.xmldataCol
FROM
(
SELECT
(
SELECT
-- HIER XML Daten generieren
'' AS 'ext:UBLExtensions',
'' AS 'ext:UBLExtensions/ext:UBLExtension',
'' AS 'ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent',
'2.1' AS 'cbc:UBLVersionID',
'TR1.2' AS 'cbc:CustomizationID',
'' AS 'cbc:ProfileID',
Rechnungen.Nummer AS 'cbc:ID',
'false' AS 'cbc:CopyIndicator',
'' AS 'cbc:UUID',
CAST(Rechnungen.Datum AS Date) AS 'cbc:IssueDate'
FROM
rechnungen
WHERE
rechnungen.id = #ID_Rechnung
FOR XML PATH(''), ROOT('Invoice')
) AS xmldataCol
This works fine - i get the following XML:
<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent />
</ext:UBLExtension>
</ext:UBLExtensions>
<cbc:UBLVersionID>2.1</cbc:UBLVersionID>
<cbc:CustomizationID>TR1.2</cbc:CustomizationID>
<cbc:ProfileID />
<cbc:ID>R200001</cbc:ID>
<cbc:CopyIndicator>false</cbc:CopyIndicator>
<cbc:UUID />
<cbc:IssueDate>2020-06-29</cbc:IssueDate>
</Invoice>
But now i need the invoice positions in the same file.
This SQL should be included in the first one and the date should be as invoice line in the xml file:
SELECT
Rechnungpos.ID AS 'cac:InvoiceLine/cbc:ID',
Rechnungpos.Anzahl AS 'cac:InvoiceLine/cbc:InvoicedQuantity'
FROM
RechnungPos
WHERE
RechnungPos.id_Rechnung = #ID_Rechnung
The output should be this:
<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent />
</ext:UBLExtension>
</ext:UBLExtensions>
<cbc:UBLVersionID>2.1</cbc:UBLVersionID>
<cbc:CustomizationID>TR1.2</cbc:CustomizationID>
<cbc:ProfileID />
<cbc:ID>R200001</cbc:ID>
<cbc:CopyIndicator>false</cbc:CopyIndicator>
<cbc:UUID />
<cbc:IssueDate>2020-06-29</cbc:IssueDate>
<cac:InvoiceLine>
<cbc:ID>1<(cbc:>
<cbc:InvoicedQuantity>3</cbc:InvoicedQuantity>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>5<(cbc:>
<cbc:InvoicedQuantity>1</cbc:InvoicedQuantity>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>9<(cbc:>
<cbc:InvoicedQuantity>2</cbc:InvoicedQuantity>
</cac:InvoiceLine>
</Invoice>
Here is the Code to generate Test Data:
CREATE TABLE [dbo].[Rechnungen](
[id] [int] NOT NULL,
[Nummer] [nvarchar](20) NOT NULL,
[Datum] [datetime] NOT NULL
)
INSERT INTO Rechnungen (id, Nummer, Datum) VALUES (8, 'R200001', '29.06.2020')
CREATE TABLE [dbo].Rechnungpos(
[id] [int] NOT NULL,
[id_Rechnung] [int] NOT NULL,
[Anzahl] [float] NOT NULL
)
INSERT INTO RechnungPos (id, id_Rechnung, Anzahl) VALUES (1, 8, 3)
INSERT INTO RechnungPos (id, id_Rechnung, Anzahl) VALUES (5, 8, 1)
INSERT INTO RechnungPos (id, id_Rechnung, Anzahl) VALUES (9, 8, 2)
it has to run on different versions - my version is SQL Server 2019
How can i do that?
Thanks for help, Thomas.
Here is how to do it.
The only complexity is how to handle a child table and specially namespaces in the output XML. That's why XQuery and its FLWOR expression are in use.
SQL
-- DDL and sample data population, start
DECLARE #Rechnungen TABLE (id int , Nummer nvarchar(20), Datum datetime);
INSERT INTO #Rechnungen (id, Nummer, Datum) VALUES
(8, 'R200001', '2020-06-29');
DECLARE #Rechnungpos TABLE (id int, id_Rechnung int, Anzahl float);
INSERT INTO #RechnungPos (id, id_Rechnung, Anzahl) VALUES
(1, 8, 3),
(5, 8, 1),
(9, 8, 2);
-- DDL and sample data population, end
DECLARE #ID_Rechnung int = 8;
;WITH XMLNAMESPACES ('urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as ext
, 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc
, 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac
, 'http://uri.etsi.org/01903/v1.3.2#' as xades
, 'http://www.w3.org/2001/XMLSchema-instance' as xsi
, 'http://www.w3.org/2000/09/xmldsig#' as ds)
SELECT (
SELECT '2.1' AS [cbc:UBLVersionID],
'TR1.2' AS [cbc:CustomizationID],
'' AS [cbc:ProfileID],
p.Nummer AS [cbc:ID],
'false' AS [cbc:CopyIndicator],
'' AS [cbc:UUID],
CAST(p.Datum AS Date) AS [cbc:IssueDate],
(
SELECT c.id AS [cbc:ID]
, CAST(c.Anzahl AS INT) AS [cbc:InvoicedQuantity]
FROM #Rechnungpos AS c INNER JOIN
#Rechnungen AS p ON p.id = c.id_Rechnung
FOR XML PATH('r'), TYPE, ROOT('root')
)
FROM #Rechnungen AS p
WHERE p.id = #ID_Rechnung
FOR XML PATH(''), TYPE, ROOT('Invoice')
).query('<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xades="http://uri.etsi.org/01903/v1.3.2#"
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent/>
</ext:UBLExtension>
</ext:UBLExtensions>
{
for $x in /Invoice/*[local-name()!="root"]
return $x,
for $x in /Invoice/root/r
return <cac:InvoiceLine>{$x/*}</cac:InvoiceLine>
}
</Invoice>');
Output
<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent />
</ext:UBLExtension>
</ext:UBLExtensions>
<cbc:UBLVersionID>2.1</cbc:UBLVersionID>
<cbc:CustomizationID>TR1.2</cbc:CustomizationID>
<cbc:ProfileID />
<cbc:ID>R200001</cbc:ID>
<cbc:CopyIndicator>false</cbc:CopyIndicator>
<cbc:UUID />
<cbc:IssueDate>2020-06-29</cbc:IssueDate>
<cac:InvoiceLine>
<cbc:ID>1</cbc:ID>
<cbc:InvoicedQuantity>3</cbc:InvoicedQuantity>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>5</cbc:ID>
<cbc:InvoicedQuantity>1</cbc:InvoicedQuantity>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>9</cbc:ID>
<cbc:InvoicedQuantity>2</cbc:InvoicedQuantity>
</cac:InvoiceLine>
</Invoice>
Thanks, Yitzhak Khabinsky for help - heres the complete solution:
DECLARE #ID_Rechnung int = 8,
#XMLData xml;
WITH XMLNAMESPACES ('urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as ext
, 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc
, 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac
, 'http://uri.etsi.org/01903/v1.3.2#' as xades
, 'http://www.w3.org/2001/XMLSchema-instance' as xsi
, 'http://www.w3.org/2000/09/xmldsig#' as ds)
SELECT
#XMLData = xmldat.xmldataCol
FROM
(
SELECT (
SELECT
-- HIER XML Daten generieren
'' AS 'ext:UBLExtensions',
'' AS 'ext:UBLExtensions/ext:UBLExtension',
'' AS 'ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent',
'2.1' AS 'cbc:UBLVersionID',
'TR1.2' AS 'cbc:CustomizationID',
'' AS 'cbc:ProfileID',
Rechnungen.Nummer AS 'cbc:ID',
'false' AS 'cbc:CopyIndicator',
'' AS 'cbc:UUID',
CAST(Rechnungen.Datum AS Date) AS 'cbc:IssueDate',
'' AS 'cbc:InvoiceTypeCode',
Rechnungen.Bemerkung1 AS 'cbc:Note',
#Waehrung AS 'cbc:DocumentCurrencyCode',
#Waehrung AS 'cbc:TaxCurrencyCode',
Rechnungen.Auftrag AS 'cac:OrderReference/cbc:ID',
-- Verkaüfer
'' AS 'cac:AccountingSupplierParty/cac:Party/cbc:EndpointID',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:StreetName',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CityName',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:PostalZone',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyId',
'VAT' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:CompanyID',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:CompanyLegalForm',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:Name',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:Telephone',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:ElectronicMail',
-- Käufer
'' AS 'cac:AccountingCustomerParty/cac:Party/cbc:EndpointID',
Rechnungen.DebKreNr AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyIdentification/cbc:ID',
Rechnungen.DebBez01 + ' ' + DebBez02 AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name',
Rechnungen.DebStrasse AS 'cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:StreetName',
Rechnungen.DebOrt AS 'cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:CityName',
Rechnungen.DebPLZ AS 'cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:PostalZone',
Rechnungen.DebLandKFZ AS 'cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode',
Rechnungen.DebUMSTID AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID',
'VAT' AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID',
Rechnungen.DebBez01 + ' ' + DebBez02 AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName',
'' AS 'cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:Name',
'' AS 'cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:Telephone',
'' AS 'cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail',
-- Kontoverbindung Verkäufer
'' AS 'cac:PaymentMeans/cbc:PaymentMeansCode',
'' AS 'cac:PaymentMeans/cac:PayeeFinancialAccount/cbc:ID',
'' AS 'cac:PaymentMeans/cac:PayeeFinancialAccount/cbc:Name',
'' AS 'cac:PaymentMeans/cac:PayeeFinancialAccount/cac:FinancialInstitutionBranch/cbc:ID',
--'' AS 'cac:PaymentTerms/cbc:Note',
-- Steuern
#Waehrung AS 'cac:TaxTotal/cbc_TaxAmount/#currencyID',
CAST(Rechnungen.BetragMWST AS nvarchar(15)) AS 'cac:TaxTotal/cbc_TaxAmount',
#Waehrung AS 'cac:TaxTotal/cac:Taxubtotal/cbc:TaxableAmount/#currencyID',
CAST(Rechnungen.BetragNetto AS nvarchar(15))AS 'cac:TaxTotal/cac:Taxubtotal/cbc:TaxableAmount',
#Waehrung AS 'cac:TaxTotal/cac:Taxubtotal/cbc:TaxAmount/#currencyID',
CAST(Rechnungen.BetragMWST AS nvarchar(15))AS 'cac:TaxTotal/cac:Taxubtotal/cbc:TaxAmount',
'' AS 'cac:TaxTotal/cac:Taxubtotal/cac:TaxCategory/cbc:ID',
CAST(Rechnungen.MWST AS nvarchar(2)) AS 'cac:TaxTotal/cac:Taxubtotal/cac:TaxCategory/cbc:Percent',
'VAT' AS 'cac:TaxTotal/cac:Taxubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID',
#Waehrung AS 'cac:LegalMonetaryTotal/cbc:LineExtensionAmount/#currencyID',
CAST(Rechnungen.BetragNetto AS nvarchar(15))AS 'cac:LegalMonetaryTotal/cbc:LineExtensionAmount',
#Waehrung AS 'cac:LegalMonetaryTotal/cbc:TaxExclusiveAmount/#currencyID',
CAST(Rechnungen.BetragNetto AS nvarchar(15))AS 'cac:LegalMonetaryTotal/cbc:TaxExclusiveAmount',
#Waehrung AS 'cac:LegalMonetaryTotal/cbc:TaxInclusiveAmount/#currencyID',
CAST(Rechnungen.BetragBrutto AS nvarchar(15))AS 'cac:LegalMonetaryTotal/cbc:TaxInclusiveAmount',
#Waehrung AS 'cac:LegalMonetaryTotal/cbc:PayableAmount/#currencyID',
CAST(Rechnungen.BetragBrutto AS nvarchar(15))AS 'cac:LegalMonetaryTotal/cbc:PayableAmount',
(
SELECT Rechnungpos.id AS [cbc:ID]
, CAST(Rechnungpos.Anzahl AS INT) AS [cbc:InvoicedQuantity]
FROM Rechnungpos WHERE RechnungPos.id_Rechnung = #id_Rechnung
FOR XML PATH('r'), TYPE, ROOT('root')
)
FROM Rechnungen
WHERE Rechnungen.id = #ID_Rechnung
FOR XML PATH(''), TYPE, ROOT('Invoice')
) AS xmldataCol
) AS xmldat;
SELECT #XMLData
.query('<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xades="http://uri.etsi.org/01903/v1.3.2#"
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
{
for $x in /Invoice/*[local-name()!="root"]
return $x,
for $x in /Invoice/root/r
return <cac:InvoiceLine>{$x/*}</cac:InvoiceLine>
}
</Invoice>');

Remove transformation is not working for a column

I am trying out a scenario where tables of two databases in MySQL are synchronized and in some places, columns are transformed. I have a perticular case where every column of DB1 table while insertion, will be synchronized (a new row will be inserted in DB2) but for updating that row, a specific column will have no effect on DB2 table (every other column will be updated). I am trying to achieve this by 'remove transformation' (one of the transformation types). But my remove transformation is not working. Other transformations are working fine. May be I have missed a thing. A little help will be much appreciated.
DB1: records_new Table: employee
CREATE TABLE `employee` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`title` varchar(11) DEFAULT 'Mr.',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
DB2: records_new_replica Table: employee
CREATE TABLE `employee` (
`id` bigint(20) NOT NULL,
`emp_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`title` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`designation` varchar(100) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`time` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
////////////////////////////////////////////////////////sym tables//////////////////////////////////////////////////////////
sym_node_group
INSERT INTO records.sym_node_group
(node_group_id, description, create_time, last_update_by, last_update_time)
VALUES('records', NULL, NULL, NULL, NULL);
INSERT INTO records.sym_node_group
(node_group_id, description, create_time, last_update_by, last_update_time)
VALUES('records-replica', NULL, NULL, NULL, NULL);
sym_node
INSERT INTO records.sym_node
(node_id, node_group_id, external_id, sync_enabled, sync_url, schema_version, symmetric_version, config_version, database_type, database_version, batch_to_send_count, batch_in_error_count, created_at_node_id, deployment_type, deployment_sub_type)
VALUES('000', 'records', '000', 1, 'http://localhost:31415/sync/records-000', '?', '3.10.4', '3.10.4', 'MySQL', '8.0', -1, -1, NULL, 'server', NULL);
INSERT INTO records.sym_node
(node_id, node_group_id, external_id, sync_enabled, sync_url, schema_version, symmetric_version, config_version, database_type, database_version, batch_to_send_count, batch_in_error_count, created_at_node_id, deployment_type, deployment_sub_type)
VALUES('2000', 'records-replica', '2000', 1, 'http://DESKTOP-KSP9CJD:31415/sync/records-replica-1000', '?', '3.10.4', '3.10.4', 'MySQL', '8.0', -1, -1, '000', 'server', NULL);
sym_router
INSERT INTO records.sym_router
(router_id, target_catalog_name, target_schema_name, target_table_name, source_node_group_id, target_node_group_id, router_type, router_expression, sync_on_update, sync_on_insert, sync_on_delete, use_source_catalog_schema, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', '', '', '', 'records', 'records-replica', 'default', '', 1, 1, 0, 1, '2019-10-30 09:40:25', NULL, '2019-10-30 09:40:25', '');
sym_trigger
INSERT INTO records.sym_trigger
(trigger_id, source_catalog_name, source_schema_name, source_table_name, channel_id, reload_channel_id, sync_on_update, sync_on_insert, sync_on_delete, sync_on_incoming_batch, name_for_update_trigger, name_for_insert_trigger, name_for_delete_trigger, sync_on_update_condition, sync_on_insert_condition, sync_on_delete_condition, custom_before_update_text, custom_before_insert_text, custom_before_delete_text, custom_on_update_text, custom_on_insert_text, custom_on_delete_text, external_select, tx_id_expression, channel_expression, excluded_column_names, included_column_names, sync_key_names, use_stream_lobs, use_capture_lobs, use_capture_old_data, use_handle_key_updates, stream_row, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-trig_new', 'records_new', '', 'employee', 'employee', 'reload', 1, 1, 0, 0, NULL, NULL, NULL, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 0, 0, 1, 1, 0, '2019-10-30 09:38:56', NULL, '2019-10-30 09:38:56', '');
sym_trigger_router
INSERT INTO records.sym_trigger_router
(trigger_id, router_id, enabled, initial_load_order, initial_load_select, initial_load_delete_stmt, ping_back_enabled, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-trig_new', 'emp-2-emp-new', 1, 1, '', '', 0, '2019-10-30 09:41:31', NULL, '2019-10-30 09:41:31', '');
sym_transform_table
INSERT INTO records.sym_transform_table
(transform_id, source_node_group_id, target_node_group_id, transform_point, source_catalog_name, source_schema_name, source_table_name, target_catalog_name, target_schema_name, target_table_name, update_first, update_action, delete_action, transform_order, column_policy, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', 'records', 'records-replica', 'LOAD', 'records_new', NULL, 'employee', 'records_new_replica', NULL, 'employee', 0, 'UPDATE_COL', 'NONE', 1, 'IMPLIED', '2019-10-30 11:38:22', NULL, '2019-10-30 11:38:22', '');
sym_transform_column
INSERT INTO records.sym_transform_column
(transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', '*', 'emp_name', 'name', 0, 'copy', '', 1, '2019-10-30 11:38:49', NULL, '2019-10-30 11:38:49', '');
INSERT INTO records.sym_transform_column
(transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', '*', 'time', NULL, 0, 'lookup', 'select UNIX_TIMESTAMP()', 1, '2019-10-31 10:01:02', NULL, '2019-10-31 10:01:02', '');
INSERT INTO records.sym_transform_column
(transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', 'U', 'title', 'title', 0, 'remove', '', 1, '2019-11-06 13:20:21', '', '2019-11-06 13:20:21', '');
Thanks in advance.:)
I wanted to delete this question. But i figured that may be...if someone stumbled upon symmetricds and after reading the user guide..missed a corner and that became a doom for him...only for those...here it goes:
In the guide, when describing fields of sym_router table, it is stated about the Use Source Catalog/Schema field that
If set then the source catalog and source schema are sent to the target to be used to find the target table.
and in appendix/ROUTER it is stated about USE_SOURCE_CATALOG_SCHEMA that,
Whether or not to assume that the target catalog/schema name should be the same as the source catalog/schema name. The target catalog or schema name will still override if not blank.
Now lets see what might override those target variables. In Transform section, they have stated the following:
Source Catalog
Name of the catalog of the configured source table. This should only be set if Use Source Catalog/Schema or Target Catalog are set on the Router.
Source Schema
Name of the schema for the configured source table. This should only be set if Use Source Catalog/Schema or Target Schema are set on the Router.
So, the resolution is, when I have set the source_catalog_name in sym_transform_table, then I have to set the use_source_catalog_schema in sym_router table and as my tables which I intended to sync is not in the default catalog then I have to explicitly set the other two columns e.g. target_catalog_name and target_table_name in sym_transform_table.
tl;dr, set the use_source_catalog_schema in table sym_router to 1 if source_catalog_name is set in the sym_transform_table for transformation and another thing...read the guide.it's brief but it's our only friend.

Salesforce data loader import error: Unable to run process accountUpsert "java.lang.RuntimeException: java.lang.NullPointerException"

I am having problem with Bulk Import to salesforce. My code and each and everything is working fine for 5000 records but i need to upsert 100,000 records.
Please Help.
Below is my error log
Creating Map
2016-08-22 12:44:12,675 FATAL [main] process.ProcessRunner topLevelError (Proce
sRunner.java:238) - Unable to run process accountUpsert
java.lang.RuntimeException: java.lang.NullPointerException
at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.ja
a:162)
at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.ja
a:100)
at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.j
va:253)
Caused by: java.lang.NullPointerException
at java.lang.String$CaseInsensitiveComparator.compare(Unknown Source)
at java.lang.String$CaseInsensitiveComparator.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at java.util.AbstractCollection.addAll(Unknown Source)
at java.util.TreeSet.addAll(Unknown Source)
at com.salesforce.dataloader.mapping.Mapper.<init>(Mapper.java:87)
at com.salesforce.dataloader.mapping.LoadMapper.<init>(LoadMapper.java:
1)
at com.salesforce.dataloader.controller.Controller.createMapper(Control
er.java:195)
at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.ja
a:146)
... 2 more
process-conf.xml file
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="accountUpsert"
class="com.salesforce.dataloader.process.ProcessRunner"
singleton="false">
<description>accountInsert job gets the account record from the CSV file
and inserts it into Salesforce.</description>
<property name="name" value="accountUpsert"/>
<property name="configOverrideMap">
<map>
<entry key="sfdc.debugMessages" value="true"/>
<entry key="sfdc.debugMessagesFile"
value="D:\Yardi\Account Upload\accountInsertSoapTrace.log"/>
<entry key="sfdc.endpoint" value="https://test.salesforce.com/"/>
<entry key="sfdc.username" value="wwaqar.yar#graymath.com.stage"/>
<!--Password below has been encrypted using key file,
therefore, it will not work without the key setting:
process.encryptionKeyFile.
The password is not a valid encrypted value,
please generate the real value using the encrypt.bat utility -->
<entry key="sfdc.password" value="5ae9e1fa9b8d55afb228898dd3ec9bb94f9d19047cb28660831286e35db82743cf488132b0ce32a0"/>
<entry key="process.encryptionKeyFile" value="D:\Yardi\Account Upload\keytext.txt"/>
<entry key="sfdc.timeoutSecs" value="600"/>
<entry key="sfdc.loadBatchSize" value="200"/>
<entry key="sfdc.entity" value="Account"/>
<entry key="process.operation" value="upsert"/>
<entry key="sfdc.externalIdField" value="Applicant_ID__c" />
<entry key="process.mappingFile" value="D:\Yardi\Account Upload\accountSunMapping.sdl"/>
<entry key="dataAccess.name"
value="D:\Yardi\Account Upload\All Applicants from 1-1-2014 to 8-17-2016 10000.csv"/>
<entry key="process.outputSuccess"
value="D:\Yardi\Account Upload\accountInsert_success.csv"/>
<entry key="process.outputError"
value="D:\Yardi\Account Upload\accountInsert_error.csv"/>
<entry key="dataAccess.type" value="csvRead"/>
<entry key="process.initialLastRunDate"
value="2005-12-01T00:00:00.000-0800"/>
</map>
</property>
</bean>
</beans>
Below is my trigger which i am using to populate some customized values before insert or update.
trigger MapStatusToStageBeforeOpportunintyCreation on Opportunity (before insert, before update) {
Set<ID> acctIDS = new Set<ID>();
Set<ID> propIDS = new Set<ID>();
String tempOppName;
for (Opportunity o : Trigger.New){
if(o.AccountId != null){
acctIDS.add(o.AccountID);
}
}
for (Opportunity o : Trigger.New){
if(o.Property_Name__c != null){
propIDS.add(o.Property_Name__c);
}
}
Map<ID, Account> acctMap = new Map<ID, Account>([Select LastName From Account Where ID =: acctIDS]);
Map<ID, Property__c> propMap = new Map<ID, Property__c>([Select Property_Code__c From Property__c Where ID =: propIDS]);
for (Opportunity o : Trigger.New){
// Mapping the StageName with Application_Status__c before Insert/update
if (o.Application_Status__c == 'Denied'){
o.StageName ='Denied';
}
else if(o.Application_Status__c == 'Approved'){
o.StageName ='Approved - Conditions Pending';
}
else if(o.Application_Status__c == 'Expired'){
o.StageName ='Expired';
}
else if(o.Application_Status__c == 'Closed'){
o.StageName ='Closed Won';
}
else if(o.Application_Status__c == 'Cancelled'){
o.StageName ='Cancelled';
}
else if(o.Application_Status__c == 'DocsSent'){
o.StageName ='Approved - Final';
}
else if(o.Application_Status__c == 'Not Submitted'){
o.StageName ='EXCLUDE FROM FILE';
}
else if(o.Application_Status__c == 'Pending'){
o.StageName ='Application Submitted';
}
else if(o.Application_Status__c == 'Submitted'){
o.StageName ='Application Submitted';
}
else if(o.Application_Status__c == 'Unprocessed'){
o.StageName ='Application Submitted';
}
else if(o.Application_Status__c == 'Null'){
o.StageName ='Error';
}
System.debug('Opp trigger is fired. ');
System.debug(o);
/*Date appSubmittedDate = o.Application_Submitted__c;
String strAppSubmittedDate = appSubmittedDate.month()+'-'+appSubmittedDate.day()+'-'+appSubmittedDate.year();
Property__c prop = [Select Property_Code__c From Property__c Where id =:o.Property_Name__c]; //Property_Name__c is returning id of related Property that's why used it's value to find Property Code.
Account acc = [Select LastName From Account Where id =:o.AccountId]; //AccountId is returning id of related Account that's why used it's value to find Account's LastName.
//o.Name = strAppSubmittedDate;
o.Name =acc.LastName+'-'+prop.Property_Code__c+'-'+strAppSubmittedDate;
//o.Name =acc.LastName+'-'+prop.Property_Code__c+'-'+String.valueOf(o.Application_Submitted__c);
//*/
for(ID acctID :acctMap.keySet()){
if(o.AccountID == acctID){
tempOppName = acctMap.get(acctID).LastName;
}
}
for(ID propID :propMap.keySet()){
if(o.Property_Name__c == propID){
tempOppName =tempOppName + '-' + propMap.get(propID).Property_Code__c;
}
}
Date appSubmittedDate = o.Application_Submitted__c;
String strAppSubmittedDate = appSubmittedDate.month()+'-'+appSubmittedDate.day()+'-'+appSubmittedDate.year();
o.Name = tempOppName + '-' + strAppSubmittedDate;
Id trigRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Sun Homes - BDS').getRecordTypeId();
o.RecordTypeId = trigRecordTypeId;
}
}
Thanks in Advance

Import parent-child XML data to Sql Server Tables

I have a XML like this:
<StateTree>
<State ID="01">
<Name>State1</Name>
<CityList>
<City ID="01" Order="1" CityGroup="1" CityBuild="1" GeoLocation="X">
<Name>City1</Name>
<Group>1</Group>
<AreaList>
<Area ID="01" GeoLocation="6">
<Name>Area1</Name>
</Area>
<Area ID="02" GeoLocation="6">
<Name>Area2</Name>
</Area>
</AreaList>
</City>
<City ID="02" Order="3" CityGroup="2" CityBuild="4" GeoLocation="5">
<Name>City2</Name>
<Group>2</Group>
<AreaList />
</City>
</CityList>
</State>
</StateTree>
and I want to convert it to tables like this:
State:
ID Name
01 State1
---------------------------------------------------
City:
ID Order CityGroup CityBuild GeoLocation Name State1
01 1 1 1 X City1 01
02 3 2 4 5 City2 01
---------------------------------------------------
AreaList:
ID GeoLocation Name CityID
01 6 Area1 01
02 6 Area2 01
How I can do this ?
thanks
I'm not going to write this for every field and all the inserts, but the following SQL should point you in the right direction:
declare #xml xml
set #xml =
'
<StateTree>
<State ID="01">
<Name>State1</Name>
<CityList>
<City ID="01" Order="1" CityGroup="1" CityBuild="1" GeoLocation="X">
<Name>City1</Name>
<Group>1</Group>
<AreaList>
<Area ID="01" GeoLocation="6">
<Name>Area1</Name>
</Area>
<Area ID="02" GeoLocation="6">
<Name>Area2</Name>
</Area>
</AreaList>
</City>
<City ID="02" Order="3" CityGroup="2" CityBuild="4" GeoLocation="5">
<Name>City2</Name>
<Group>2</Group>
<AreaList />
</City>
</CityList>
</State>
</StateTree>
'
--Select States
select
ID = s.value('#ID','varchar(10)'),
Name = s.value('Name[1]','varchar(100)')
from
#xml.nodes('/StateTree/State') x(s)
--Select Cities
select
ID = c.value('#ID','varchar(10)'),
Name = c.value('Name[1]','varchar(100)'),
StateID = c.value('../../#ID','varchar(10)')
from
#xml.nodes('/StateTree/State/CityList/City') x(c)
--Select Areas
select
ID = a.value('#ID','varchar(10)'),
Name = a.value('Name[1]','varchar(100)'),
CityID = a.value('../../#ID','varchar(10)')
from
#xml.nodes('/StateTree/State/CityList/City/AreaList/Area') x(a)

Resources