Regrouping groups in SQL Server - sql-server

I am trying to solve the below problem, I have an existing dataset that is already grouped, but I need to it to be grouped further based on the common "SO_Number" in the dataset, example below:
Current Data:
Group_Key
SO_Number
233738
SO21268046
233738
SO21269767
234129
SO21269767
234129
SO21274404
234129
SO21271542
234129
SO21274421
234421
SO21274421
234421
SO21276633
234421
SO21276877
88964
SO21276877
88964
SO21278203
88964
SO21278329
234727
SO21278329
234727
SO21279199
234727
SO21279542
91016
SO21279542
91016
SO21289940
88111
SO21289664
88111
SO21289665
88112
SO21289665
88112
SO21289677
88113
SO21289678
Expected Data output:
NewGroup_Key
Group_key
SO_number
233738,234129,234421,88964,234727,91016
233738
SO21268046
233738,234129,234421,88964,234727,91016
233738
SO21269767
233738,234129,234421,88964,234727,91016
234129
SO21269767
233738,234129,234421,88964,234727,91016
234129
SO21274404
233738,234129,234421,88964,234727,91016
234129
SO21271542
233738,234129,234421,88964,234727,91016
234129
SO21274421
233738,234129,234421,88964,234727,91016
234421
SO21274421
233738,234129,234421,88964,234727,91016
234421
SO21276633
233738,234129,234421,88964,234727,91016
234421
SO21276877
233738,234129,234421,88964,234727,91016
88964
SO21276877
233738,234129,234421,88964,234727,91016
88964
SO21278203
233738,234129,234421,88964,234727,91016
88964
SO21278329
233738,234129,234421,88964,234727,91016
234727
SO21278329
233738,234129,234421,88964,234727,91016
234727
SO21279199
233738,234129,234421,88964,234727,91016
234727
SO21279542
233738,234129,234421,88964,234727,91016
91016
SO21279542
233738,234129,234421,88964,234727,91016
91016
SO21289940
88111,88112
88111
SO21289665
88111,88112
88112
SO21289677
88113
88113
SO21289678
The expected data output I need should be in three groups instead of nine groups as they're all grouped by SO_Number - hence creating a new group key (NewGroup_Key) that will be used for new mapping of the data. Note that this is just a subset of the dataset so there are other groups that are involved as well. I have bolded the SO_number where each of the groups should be linked(grouped) in the "Current Data" table.
I have tried a few queries my end but didn't lead to anything reasonable or easy to follow using SQL. So any ideas would be helpful.

Hen you say 'clustering' are you referring to this?
declare #t TABLE (
category int NOT NULL
,segment NVARCHAR(50) NOT NULL
,payment int NOT NULL
);
INSERT INTO #t(category,segment,payment) VALUES (01,'A',1425);
INSERT INTO #t(category,segment,payment) VALUES (01,'B',7647);
INSERT INTO #t(category,segment,payment) VALUES (01,'A',6164);
INSERT INTO #t(category,segment,payment) VALUES (01,'B',3241);
--if you want payment column as string then use following
SELECT
category,
segment,
STRING_AGG(cast(payment as nvarchar(50)),'+') payment
FROM
#t T
GROUP BY
category,segment
Result:

Related

SQL Server - XQuery: delete parent node based on child value substring

I want to delete all parent nodes TxDtls of the following XML where position 20 of child value Ref is 2.
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.04" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:camt.054.001.04 camt.054.001.04.xsd">
<BkToCstmrDbtCdtNtfctn>
<Ntfctn>
<Ntry>
<TtlChrgsAndTaxAmt Ccy="CHF">1.60</TtlChrgsAndTaxAmt>
<Rcrd>
<Amt Ccy="CHF">1.60</Amt>
<CdtDbtInd>DBIT</CdtDbtInd>
<ChrgInclInd>false</ChrgInclInd>
<Tp>
<Prtry>
<Id>2</Id>
</Prtry>
</Tp>
</Rcrd>
</Chrgs>
<NtryDtls>
<TxDtls>
<RmtInf>
<Strd>
<CdtrRefInf>
<Ref>111118144400000000020076766</Ref>
</CdtrRefInf>
</Strd>
</RmtInf>
</TxDtls>
<TxDtls>
<RmtInf>
<Strd>
<CdtrRefInf>
<Ref>111117645600000000030076281</Ref>
</CdtrRefInf>
</Strd>
</RmtInf>
</TxDtls>
</NtryDtls>
</Ntry>
</Ntfctn>
</BkToCstmrDbtCdtNtfctn>
</Document>
So I want to delete the first TxDtls node (substring position 20 = 2) while I want to keep the second one (substring position 20 <> 2).
I tried this:
UPDATE mytable SET XMLData.modify('delete .//TxDtls[RmtInf/Strd/CdtrRefInf/Ref/substring(text(),20,1) = ''2'']')
However, I get the error "The XQuery syntax '/function()' is not supported". Any hints on how to achieve this?
Thanks
What a difference made by the partially provided minimal reproducible example.
The XML is still not well-formed. I had to comment out the following tag: </Chrgs>
A default namespace is easily handled by its declaration in the XQuery method.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, xmldata XML);
INSERT INTO #tbl (xmldata) VALUES
(N'<?xml version="1.0"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.04"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:camt.054.001.04 camt.054.001.04.xsd">
<BkToCstmrDbtCdtNtfctn>
<Ntfctn>
<Ntry>
<TtlChrgsAndTaxAmt Ccy="CHF">1.60</TtlChrgsAndTaxAmt>
<Rcrd>
<Amt Ccy="CHF">1.60</Amt>
<CdtDbtInd>DBIT</CdtDbtInd>
<ChrgInclInd>false</ChrgInclInd>
<Tp>
<Prtry>
<Id>2</Id>
</Prtry>
</Tp>
</Rcrd>
<!--</Chrgs>-->
<NtryDtls>
<TxDtls>
<RmtInf>
<Strd>
<CdtrRefInf>
<Ref>111118144400000000020076766</Ref>
</CdtrRefInf>
</Strd>
</RmtInf>
</TxDtls>
<TxDtls>
<RmtInf>
<Strd>
<CdtrRefInf>
<Ref>111117645600000000030076281</Ref>
</CdtrRefInf>
</Strd>
</RmtInf>
</TxDtls>
</NtryDtls>
</Ntry>
</Ntfctn>
</BkToCstmrDbtCdtNtfctn>
</Document>');
-- DDL and sample data population, end
-- before
SELECT * FROM #tbl;
UPDATE #tbl SET xmldata.modify('declare default element namespace "urn:iso:std:iso:20022:tech:xsd:camt.054.001.04";
delete /Document/BkToCstmrDbtCdtNtfctn/Ntfctn/Ntry/NtryDtls/TxDtls[RmtInf/Strd/CdtrRefInf/Ref[substring(./text()[1],20,1) = "2"]]');
-- after
SELECT * FROM #tbl;

Adding node to SQL Server XML is silently failing

Trying to figure out why this snippet does not work.
DECLARE #changeStatus XML, #changeSet XML
SELECT #changeSet = TOP 1 ChangeSet
FROM MyTable
SET #changeStatus = '<change id="' + CAST(NEWID() AS NVARCHAR(36)) + '" by="' + #authorizingUserName + '" byAccountId="' + CAST(#authorizingUserId AS NVARCHAR(36)) + '" when="' + CONVERT(NVARCHAR(50),GETUTCDATE(),127) + 'Z">'
+ '<property id="Status" name="Status" old="' + #status + '" new="Closed" />'
+ '<collections />'
+ '</change>'
-- THIS DOES NOT ERROR OUT AND DOES NOT DO ANYTHING!!
SET #changeSet.modify('insert sql:variable("#changeStatus") as last into (/changes)[1]')
The overall structure of the XML is:
<changes>
<change id="" by="" byAccountId="" when="">
<property />
<collections />
</change>
</changes>
When I run the script and check the #changeSet before and after processing, they are identical. i.e.: The #changeStatus was never added to the XML contained in #changeSet.
If the original was:
<changes>
<change id="change01" by="" byAccountId="" when="">
<property ... />
<collections />
</change>
<change id="change02" by="" byAccountId="" when="">
<property ... />
<collections />
</change>
</changes>
I expected to see:
<changes>
<change id="change01" by="" byAccountId="" when="">
<property ... />
<collections />
</change>
<change id="change02" by="" byAccountId="" when="">
<property ... />
<collections />
</change>
<change id="82ECB3C5-D3BA-4CD2-B62C-89C083E4BAA1" by="me#mydomain.com" byAccountId="1E910737-D78C-E711-9C04-00090FFE0001" when="2018-01-17T00:12:33.700Z">
<property id="Status" name="Status" old="In Review" new="Closed" />
<collections />
</change>
</changes>
Does anyone see what might be wrong?
You should never create an XML on string level!
This has various side-effects.
If one of the variables is NULL the whole string will be NULL
Try SELECT '<x>' + NULL + '</x>';
XML is not just text with some fancy extras. Using T-SQL's FOR XML will - for sure! - create valid XML. Now imagine one of your string contains forbidden characters...
Try SELECT '<x>' + 'The arrow "->" might appear in normal text' + '</x>';
And try to cast it to XML
Many values are not stored in readable format but in some binary format. Depending on your system's settings the conversion of such types (numbers, date and time, BLOBs) will vary. Using FOR XML will use - for sure! - the correct format in and out. You can write anything within your XML, but on another system it might fail to read it.
Try it this way:
DECLARE #changeSet XML = N'<changes/>';
DECLARE #changeStatus XML;
SET #changeStatus=
(
SELECT NEWID() AS [#id]
,'SomeAuthor' AS [#by]
,'SomeAuthorId' AS [#byAccountId]
,GETUTCDATE() AS [#when]
,'Status' AS [property/#id]
,'Status' AS [property/#name]
,'In Review' AS [property/#old]
,'Closed' AS [property/#new]
,'' AS [collections]
FOR XML PATH('change')
);
--your code works fine
SET #changeSet.modify(N'insert sql:variable("#changeStatus") as last into (/changes)[1]');
--you see the first change integrated
SELECT #changeSet;
--Now let us create one more element
SET #changeStatus=
(
SELECT NEWID() AS [#id]
,'Another' AS [#by]
,'OneMore' AS [#byAccountId]
,GETUTCDATE() AS [#when]
,'Status' AS [property/#id]
,'Status' AS [property/#name]
,'In Review' AS [property/#old]
,'Closed' AS [property/#new]
,'' AS [collections]
FOR XML PATH('change')
);
--and insert it
SET #changeSet.modify(N'insert sql:variable("#changeStatus") as last into (/changes)[1]');
--yeah, worked!
SELECT #changeSet;
The query you posted works in general. I ran following test:
http://rextester.com/RNX55555
However, if any of the injected parameters is null, the change will not be inserted and no error will be thrown as you try to insert NULL aka nothing.

Querying (a lot of) XML data for specific text with in xml Elements (Tsql)

Sorry: this post got a little long (wanted to make sure everything relevant was in)
Struggling to wrap my brain around this a little.
I have a table that has 5 columns
ID (varchar)
Record value(XML)
date (datetime)
applicationtypeid (int)
applicationstatusid(int)
XML contains alot of data but part i'm interested in looks like this.
<GoodsAndServicesItemSummaryViewModelItems>
<GoodsAndServicesMasterViewModel>
<Id>1</Id>
<ClassId>1</ClassId>
<TermsText>text</TermsText>
<TermsCreationType>ManuallyEntered</TermsCreationType>
<Terms />
Specifically the "TermsCreationType" element. In it can be one of the following 3 strings:
ManuallyEntered
CopyFromExistingMarks
CopyFromPreapprovedTermsDatabase
Depending on what the customer files there could also be a mixture of all three and they could contain as many of these mixtures as they theoretically wanted i.e.:
</PriorityClaimAdditionalDetailWizardStepViewModel>
<GoodsAndServicesMasterViewModel>
<Id>9</Id>
<ClassId>2</ClassId>
<TermsText>texty</TermsText>
<TermsCreationType>ManuallyEntered</TermsCreationType>
<Terms />
</GoodsAndServicesMasterViewModel>
<GoodsAndServicesMasterViewModel>
<Id>10</Id>
<ClassId>1</ClassId>
<TermsText>text</TermsText>
<TermsCreationType>ManuallyEntered</TermsCreationType>
<Terms />
</GoodsAndServicesMasterViewModel>
</GoodsAndServicesItemSummaryViewModelItems>
<GoodsAndServicesItemSummaryViewModelItemsUnMerged>
<GoodsAndServicesMasterViewModel>
<Id>9</Id>
<ClassId>9</ClassId>
<TermsText>test</TermsText>
<TermsCreationType>CopyFromExistingMarks</TermsCreationType>
<Terms />
</GoodsAndServicesMasterViewModel>
I'm trying to find a count of how many records from a certain date range that
ONLY contain one of the aforementioned (whether it appears once or even 50 times as long as that's the only value in that element)
Records that contain any mixture of the three.
My attempt so far, for the "one element only" is thus:
SELECT Count (id) [pre-approved only]
FROM [TMWebForms].[dbo].[webformapplication]
WHERE trademarkid NOT IN (SELECT id
FROM [TMWebForms].[dbo].[webformapplication]
WHERE applicationtypeid = '5'
AND createddate BETWEEN '2016-08-01' AND '2016-08-31'
AND RECORDDATA.value('contains((//GoodsAndServicesWizardStepViewModel/GoodsAndServicesItemSummaryViewModelItems/GoodsAndServicesMasterViewModel/TermsCreationType/text())[1], "ManuallyEntered")', 'bit') = 1
AND applicationstatusid = 50
AND applicationtypeid = 5)
AND id NOT IN (SELECT id
FROM [TMWebForms].[dbo].[webformapplication]
WHERE applicationtypeid = '5'
AND createddate BETWEEN '2016-08-01' AND '2016-08-31'
AND RECORDDATA.value('contains((//GoodsAndServicesWizardStepViewModel/GoodsAndServicesItemSummaryViewModelItems/GoodsAndServicesMasterViewModel/TermsCreationType/text())[1], "CopyFromExistingMark")', 'bit') = 1
AND applicationstatusid = 50
AND applicationtypeid = 5)
AND createddate BETWEEN '2016-08-01' AND '2016-08-31'
AND RECORDDATA.value('contains((//GoodsAndServicesWizardStepViewModel/GoodsAndServicesItemSummaryViewModelItems/GoodsAndServicesMasterViewModel/TermsCreationType/text())[1], "CopyFromPreapprovedTermsDatabase")', 'bit') = 1
AND applicationstatusid = 50
AND applicationtypeid = 5
This is long winded and not the best performance wise by a long shot! (i thought about converting it to a string then using "like" - but that is probably just as bad, if not worse)
It doesn't pull exactly what i wanted back. To me it is searching only for "CopyFromPreapprovedTermsDatabase", but when interrogating the data, There are a few cases where this is the first line but, i can also see "manuallyentered" exists.
Any help appreciated here!
Try it like this
(I had to add a root and add some opening and closing tags)
DECLARE #xml XML=
N'<SomeRoot>
<GoodsAndServicesItemSummaryViewModelItems>
<GoodsAndServicesMasterViewModel>
<Id>9</Id>
<ClassId>2</ClassId>
<TermsText>texty</TermsText>
<TermsCreationType>ManuallyEntered</TermsCreationType>
<Terms />
</GoodsAndServicesMasterViewModel>
<GoodsAndServicesMasterViewModel>
<Id>10</Id>
<ClassId>1</ClassId>
<TermsText>text</TermsText>
<TermsCreationType>ManuallyEntered</TermsCreationType>
<Terms />
</GoodsAndServicesMasterViewModel>
</GoodsAndServicesItemSummaryViewModelItems>
<GoodsAndServicesItemSummaryViewModelItemsUnMerged>
<GoodsAndServicesMasterViewModel>
<Id>9</Id>
<ClassId>9</ClassId>
<TermsText>test</TermsText>
<TermsCreationType>CopyFromExistingMarks</TermsCreationType>
<Terms />
</GoodsAndServicesMasterViewModel>
</GoodsAndServicesItemSummaryViewModelItemsUnMerged>
</SomeRoot>';
DECLARE #tbl TABLE(ID VARCHAR(10),Record_Value XML,[date] DATETIME,applicationtypeid INT,applicationstautsid INT);
INSERT INTO #tbl VALUES('SomeTest',#xml,GETDATE(),11,22);
--The CTE will select all columns and add the actual count of the TermsCreationType with the given text()
WITH CTE AS
(
SELECT *
,Record_Value.value('count(//TermsCreationType[text()="ManuallyEntered"])','int') AS CountManuallyEntered
,Record_Value.value('count(//TermsCreationType[text()="CopyFromExistingMarks"])','int') AS CountCopyFromExistingMarks
,Record_Value.value('count(//TermsCreationType[text()="CopyFromPreapprovedTermsDatabase"])','int') AS CountCopyFromPreapprovedTermsDatabase
FROM #tbl
)
--The final SELECT uses as big CASE WHEN hierarchy to analyse the counts
SELECT *
,CASE WHEN CTE.CountManuallyEntered=0 AND CTE.CountCopyFromExistingMarks=0 AND CTE.CountCopyFromPreapprovedTermsDatabase=0 THEN 'None'
ELSE
CASE WHEN CTE.CountManuallyEntered>0 AND CTE.CountCopyFromExistingMarks=0 AND CTE.CountCopyFromPreapprovedTermsDatabase=0 THEN 'Manually'
ELSE
CASE WHEN CTE.CountManuallyEntered=0 AND CTE.CountCopyFromExistingMarks>0 AND CTE.CountCopyFromPreapprovedTermsDatabase=0 THEN 'Existing'
ELSE
CASE WHEN CTE.CountManuallyEntered=0 AND CTE.CountCopyFromExistingMarks=0 AND CTE.CountCopyFromPreapprovedTermsDatabase>0 THEN 'Preapproved'
ELSE
'Mixed'
END
END
END
END AS CountAnalysis
FROM CTE;

Querying XML within SQL Server with namespace

I'm trying to query some XML data that I was sent. I have followed various examples, but can't even address any of the elements beneath the root. I'm not sure what I'm missing. I've tried simply pulling the xml beneath /KitchenSupply/StoreInfo and nothing. Is the namespace the culprit for me not being able to return anything?
declare #myxmlinv as xml =
'<?xml version="1.0" encoding="utf-8"?>
<KitchenSupply xmlns="http://www.starstandards.org/STAR" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="KitchenSupply.xsd">
<StoreInfo>
<RCPT>
<SubTaskCode>ZZZ</SubTaskCode>
<SubComponentCode>BS1</SubComponentCode>
<StoreNumber>2241</StoreNumber>
<USRegionNumber>SE</USRegionNumber>
</RCPT>
<SentDateTime>02/04/2015</SentDateTime>
<IntId>ABC1234587</IntId>
<Destinations>
<DestinationFormatType>KS_XML_v3</DestinationFormatType>
</Destinations>
</StoreInfo>
<KitchenOrder>
<KsRecord SalesTransactionPayType="CC" SalesTransactionType="Closed">
<ReceiptAmt RcptTotalAmt="0.00" CustRcptTotalAmt="25.22" CCPostDate="01/07/2015" InvoiceDate="01/05/2015" CustName="JOHN SMITH" CustNo="13998" RcptNo="78476221" />
<KsCosts>
<SaleAmts UnitCost="15.00" TxblAmt="15.00" PayType="Cust" />
<SalesInfo JobStatus="F" JobNo="1" ItemCode="HT093" ItemDesc="Hand Towel">
<EmpInfo EmpRate="16.00" EmpCommPct="1.2" EmpName="DOUG ROGERS" EmpNo="998331" />
</SalesInfo>
</KsCosts>
</KsRecord>
<CustomerRecord>
<ContactInfo LastName="SMITH" FreqFlag="Y">
<Address Zip="90210" State="CA" City="BEV" Addr1="123 MAIN ST" Type="Business" />
<Email MailTo="FAKE#USA.COM" />
<Phone Num="1235551212" Type="H" />
<Phone Num="1235551213" Type="B" />
</ContactInfo>
</CustomerRecord>
</KitchenOrder>
<KitchenOrder>
<KsRecord SalesTransactionPayType="CC" SalesTransactionType="Closed">
<ReceiptAmt RcptTotalAmt="0.00" CustRcptTotalAmt="5.71" CCPostDate="01/08/2015" InvoiceDate="01/07/2015" CustName="SARAH BALDWIN" CustNo="14421" RcptNo="78476242" />
<KsCosts>
<SaleAmts UnitCost="2.00" TxblAmt="2.00" PayType="Cust" />
<SalesInfo JobStatus="F" JobNo="1" ItemCode="HS044" ItemDesc="Hand Soap">
<EmpInfo EmpRate="16.00" EmpCommPct="1.2" EmpName="DOUG ROGERS" EmpNo="998331" />
</SalesInfo>
</KsCosts>
</KsRecord>
<CustomerRecord>
<ContactInfo LastName="BALDWIN" FreqFlag="N">
<Address Zip="90210" State="CA" City="BEV" Addr1="123 VINE ST" Type="Home" />
<Email MailTo="FAKESARAH#USA.COM" />
<Phone Num="1235555512" Type="H" />
<Phone Num="1235556613" Type="M" />
</ContactInfo>
</CustomerRecord>
</KitchenOrder>
</KitchenSupply>';
declare #myxmlinv_table as table (
row_id tinyint,
inv_xml xml
);
insert into #myxmlinv_table(row_id,inv_xml) values('1',#myxmlinv);
Display the XML document and pull the IntId column: (doesn't work)
select i.row_id, i.inv_xml, i.inv_xml.value('(/KitchenSupply/StoreInfo/IntId)[1]','varchar(255)') as data_description
from #myxmlinv_table i
Attempt to use XMLNAMESPACES to display the XML document at the StoreInfo level: (also doesn't work)
WITH XMLNAMESPACES ('http://www.starstandards.org/STAR' as ks)
SELECT
XmlCol.query('/ks:KitchenSupply/StoreInfo')
FROM T;
Ideally, I'd like to use the nodes to extract all the data out and in to separate tables for querying.
KitchenOrders all within one table, CustomerRecord within another, etc.
Any ideas?
You need to use something like this:
-- define the XML namespace as the "default" so you don't have to
-- prefix each and every XPath element with the XML namespace prefix
WITH XMLNAMESPACES( DEFAULT 'http://www.starstandards.org/STAR')
SELECT
-- reach into the <KsRecord> subnode under <KitchenOrder>
ReceiptNo = XC.value('(KsRecord/ReceiptAmt/#RcptNo)[1]', 'int'),
CustName = XC.value('(KsRecord/ReceiptAmt/#CustName)[1]', 'varchar(25)'),
-- reach into the <CustomerRecord> subnode under <KitchenOrder>
CustomerLastName = xc.value('(CustomerRecord/ContactInfo/#LastName)[1]', 'varchar(50)'),
CustomerEmail = xc.value('(CustomerRecord/ContactInfo/Email/#MailTo)[1]', 'varchar(50)')
FROM
-- get a "virtual" table of XML fragments, one for each <KitchenOrder> node
#myxmlinv.nodes('/KitchenSupply/KitchenOrder') AS XT(XC)
Yes, it's the namespace. To get SQL Server to ignore the namespace you can use local-name:
SELECT *
FROM #myxmlinv_table
WHERE inv_xml.exist('//*[local-name()="KitchenSupply"]') = 1

Using substring to strip text from text file & insert into SQL Server database & create script text file as result

Database Specification: SQL Server 2012
Problem Statement:
I need a sql query (store procedure or function or set-base query … you the expert) to assist with processing 4.1 million records in efficient time. These records reside in a text file and therefore need to inserted into a database table. Note each record consist of the following fields at different offset values:
Herewith the offset values for only the first 6 columns...
,LTRIM(SUBSTRING([TABLE],1,13)) --National_id
,LTRIM(SUBSTRING([TABLE],14,43)) --Errmsg
,LTRIM(SUBSTRING([TABLE],57,8)) --DeceasedDTE
,LTRIM(SUBSTRING([TABLE],65,50)) --DeceasedReason
,LTRIM(SUBSTRING([TABLE],115,45)) --Surname
,LTRIM(SUBSTRING([TABLE],158,50)) --FirstNames
Note the FirstNames column could contain 3 string values separated by a space … FName1, FName2, Fname3…
This is where I’m struggling to strip this column with more than 2 string values … only because this column doesn’t work with offset values …
I have the following 3 records as a sample ... these records need to be stored in a text file and used as input..
Copy this to a text file named: Deceased.txt
000101001118 IDENTITY NUMBER NOT NUMERIC
0001010061181PERSON DECEASED 19990101OBSTRUCTIVE AIRWAYS SYNDROME BABA NOWEZILE
0001010077097 COERTZEN AZIL CUBITT JONO
Desired Result:
1. Insert each record to a sql server table.
The table will have the following columns:
National_id Errmsg DeceasedDTE DeceasedReason Surname FirstNames
First_Initial Second_Initial Third_Initial FName1 FName2 FName3
Also note the FirstNames is separated with a space and I need them spit up into each FName1, FName2 and FName3 ... with its corresponding first letter that makes up the initial..
I then need to create a script send to a .txt file that creates an insert statement for each record with the following columns... national_id, surname, First_Initial, Second_Initial,Third_Initial, First_Name, Second_Name, Third_Name
E.G.
Set #Insert = "insert into prodmgr.t_unverified (national_id, surname, First_Initial, Second_Initial,Third_Initial, First_Name, Second_Name, Third_Name) values ('"
NOTE:
DECEASED.TXT (3 RECORDS)
000101001118 IDENTITY NUMBER NOT NUMERIC
0001010061181PERSON DECEASED 19990101OBSTRUCTIVE AIRWAYS SYNDROME BABA NOWEZILE
0001010077097 COERTZEN AZIL CUBITT JONO
TABLE:DECEASED (3 RECORDS)
National_id Errmsg DeceasedDTE DeceasedReason Surname FirstNames First_Initial Second_Initial Third_Initial FName1 FName2 FName3
RESULT IN TEXT FILE: (2 RECORDS)
insert into prodmgr.t_unverified (national_id, surname, First_Initial, Second_Initial,Third_Initial, First_Name, Second_Name, Third_Name) values ('0001010061181',’BABA’,’N’,’’,’’,’NOWEZILE’,’’,’’)
insert into prodmgr.t_unverified (national_id, surname, First_Initial, Second_Initial,Third_Initial, First_Name, Second_Name, Third_Name) values (0001010077097,’COERTZEN’,’A’,’C’,’J’,’AZIL’,’CUBITT’,’JONO’)

Resources