Handle XML data that is in single quote while loading - sql

Can anybody tell me how to load below data into database.
declare #learnxml varchar(5000);set #learnxml = '<alerts><alert id="i-20200107-1"><alertTime>2020-01-07T00:13:07.000-0500</alertTime><text>See the attached CSV for details (Click 'Export Attachment' at the top of the screen).</text> <state> <alertStatus>New</alertStatus> <alertAssignee/> </state> <alertCount>1</alertCount> <startTime>2020-01-07T00:13:07.000-0500</startTime> </alert> </alerts>';DECLARE #fileDataX XML = #learnxml PRINT #learnxml;SELECT xData.value('../#id','Varchar(100)') AlertId,
xData.value('../alertTime[1]','VARCHAR(50)') AlertTime,
xData.value('../text[1]','varchar(max)') AlertText,
xData.value('../alertCount[1]','int') AlertCount,
xData.value('../startTime[1]','VARCHAR(50)') AlertStartTime,
xData.value('(.)/alertStatus[1]', 'varchar(100)') AlertStatus,
xData.value('(.)/alertAssignee[1]', 'varchar(100)') AlertAssignee FROM #fileDataX.nodes('./alerts/alert/state') as x(xData)
Above query gives me an error
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near 'Export'.

A literal string in TSQL is enclosed in single quote characters: '. Any single quotes that need to appear in the string must be escaped by using two consecutive single quote characters: ''
So
declare #learnxml varchar(5000);
set #learnxml = '<alerts><alert id="i-20200107-1"><alertTime>2020-01-07T00:13:07.000-0500</alertTime><text>See the attached CSV for details (Click ''Export Attachment'' at the top of the screen).</text> <state> <alertStatus>New</alertStatus> <alertAssignee/> </state> <alertCount>1</alertCount> <startTime>2020-01-07T00:13:07.000-0500</startTime> </alert> </alerts>';
DECLARE #fileDataX XML = #learnxml
PRINT #learnxml;
SELECT
xData.value('../#id','Varchar(100)') AlertId,
xData.value('../alertTime[1]','VARCHAR(50)') AlertTime,
xData.value('../text[1]','varchar(max)') AlertText,
xData.value('../alertCount[1]','int') AlertCount,
xData.value('../startTime[1]','VARCHAR(50)') AlertStartTime,
xData.value('(.)/alertStatus[1]', 'varchar(100)') AlertStatus,
xData.value('(.)/alertAssignee[1]', 'varchar(100)') AlertAssignee
FROM #fileDataX.nodes('./alerts/alert/state') as x(xData)

Related

Replace function requires 3 arguments

I am trying to fetch data from SQL to excel and it is giving me the below error
My Query in SQL Server
DECLARE #Delimiter Char(1)
SET #Delimiter = CHAR(9)
EXEC MSDB.dbo.sp_Send_DBMail
#profile_name = 'K2MailSetup',
#Recipients='abs#test.com',
#Subject='Extraction Report',
#Body='Hi,
Please find attached extraction report as required. ',
#Query='set nocount on;Select Coalesce(replace(replace(A.[type], char(10), ''), char(13), ''),'') as Type FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A',
#Attach_Query_Result_As_File = 1,
#Query_Result_Header = 1,
#Query_Attachment_Filename = 'Report.csv',
#Query_Result_Separator = #Delimiter,
#query_result_width =32767,
#query_result_no_padding=1
========================================================================
It is giving me below error
Msg 22050, Level 16, State 1, Line 0
Error formatting query, probably invalid parameters
Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 517
Query execution failed: Msg 105, Level 15, State 1, Server MYKULK2DB01Q\MSSQLSTG, Line 1
Unclosed quotation mark after the character string ') as Type
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A
'.
Msg 102, Level 15, State 1, Server MYKULK2DB01Q\MSSQLSTG, Line 1
Incorrect syntax near ') as Type
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A
========================================================================
The strange thing is that when I just run the query it provides me result but when I try to create report out of it by using the above excel steps and parameters it gives me error.
You need to check the quote in the #Query variable.
I replaced it in the following;
#Query='set nocount on;Select Coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A'
From the docs: SQL Server Replace
The syntax for REPLACE() goes as follows:
REPLACE ( string_expression , string_pattern , string_replacement )
As you can see, all parameters should be in string format. Make sure all parameters are encased in '' for your script to work.

Control characters handling in XML

I am following XML based transport of data using FOR XML AUTO. When a column containing control character was encountered and a XML transform as below was attempted, it resulted in an exception:
DECLARE #TrialData NVARCHAR(200) = ''; --Not empty string..contains a control character '<-'
DECLARE #TrialDataInHex VARBINARY(100)
SET #TrialDataInHex = CONVERT(VARBINARY(100),#TrialData)
SELECT #TrialDataInHex; -- returns 0x1B00 looks like this '<-'
Now, when I try to insert the same into XML variable like below
DECLARE #a_XML XML;
SET #a_XML = #TrialData;
This resulted in
XML parsing: line 0, character 0, unrecognized input signature
Can Anyone suggest how control characters are usually handled when XML FROM SQL data medium is used?
You have to wrap that value in an XML element:
XMLELEMENT("TrialData" , #TrialData)
generates
<TrialData>←</TrialData>

cast text to xml error illegal qualified name character

how to fix error illegal qualified name character in this sample :
Declare #Str As nvarchar(256)
Set #Str = N'<Log "ReceiptStockHNo="2" ReceiptStockHDate="Feb 4 2" Comment="" />'
Select Cast(#Str As xml)
Error :
Msg 9455, Level 16, State 1, Line 5
XML parsing: line 1, character 6, illegal qualified name character
What is this extra " ? .
Remove the " and it will work.
Additional information :
To prevent future errors for needed encoded characters like & , < , use the appropriate replacement :
Declare #Str As nvarchar(256)
Set #Str = '<tag>&</tag>'
Select Cast(#Str As xml)
Will yield :
Msg 9421, Level 16, State 1, Line 3 XML parsing: line 1, character 7
illegal name character
While changing < to < :
Declare #Str As nvarchar(256)
Set #Str = '<tag><</tag>'
Select Cast(#Str As xml)
Will be Ok.

SQL Replace and where CAST(PromotionRuleData as NVARCHAR(MAX))

Can't seem to edit my old post but I am trying to execute this SQL script
UPDATE Promotions
set Description = '£5 Off £25 Spend',
UsageText = '£5 Off £25 Spend',
EmailText = '£5 Off £25 Spend',
PromotionRuleData= '<ArrayOfPromotionRuleBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><PromotionRuleBase xsi:type="StartDatePromotionRule"><StartDate>2013-11-18T00:00:00</StartDate></PromotionRuleBase><PromotionRuleBase xsi:type="ExpirationDatePromotionRule"><ExpirationDate>2014-01-13T00:00:00</ExpirationDate></PromotionRuleBase><PromotionRuleBase xsi:type="ExpirationNumberOfUsesPerCustomerPromotionRule"><NumberOfUsesAllowed>1</NumberOfUsesAllowed> </PromotionRuleBase><PromotionRuleBase xsi:type="MinimumCartAmountPromotionRule"><CartAmount>24.99</CartAmount></PromotionRuleBase></ArrayOfPromotionRuleBase>',
PromotionDiscountData = '<ArrayOfPromotionDiscountBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><PromotionDiscountBase xsi:type="OrderPromotionDiscount"><DiscountType>Fixed</DiscountType><DiscountAmount>5.00</DiscountAmount></PromotionDiscountBase></ArrayOfPromotionDiscountBase>'
where Name = 'test1,test2,etc...'
It comes back with this error
Msg 402, Level 16, State 1, Line 1
The data types varchar and text are incompatible in the equal to operator.
I try to use where CAST(PromotionRuleData as NVARCHAR(MAX))
So the line reads as
CAST(PromotionRuleData as NVARCHAR(MAX)) = '<ArrayOfPromotionRuleBase ...
but no luck.
You cannot compare a string literal against a text column in SQL Server.
Which column is of datatype text ? Your name column that you use in the WHERE clause by any chance?
If so, use this WHERE instead:
WHERE CAST(Name AS VARCHAR(MAX)) = 'test1,test2,etc...'
or better yet: convert your column to a more appropriate datatype like VARCHAR(n) (unless you really need 2 GB = 2 billion characters - if so, then use VARCHAR(MAX))

Updating part of a SQL cell

Trying to run this SQL script
update Promotions
set PromotionDiscountData = '<ArrayOfPromotionRuleBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><PromotionRuleBase xsi:type="StartDatePromotionRule"><StartDate>2013-11-11T00:00:00</StartDate></PromotionRuleBase><PromotionRuleBase xsi:type="ExpirationDatePromotionRule"><ExpirationDate>2014-01-12T00:00:00</ExpirationDate></PromotionRuleBase><PromotionRuleBase xsi:type="ExpirationNumberOfUsesPerCustomerPromotionRule"><NumberOfUsesAllowed>1</NumberOfUsesAllowed></PromotionRuleBase><PromotionRuleBase xsi:type="ProductIdPromotionRule"><ProductIds><int>55232</int></ProductIds><RequireQuantity>false</RequireQuantity><Quantity>1</Quantity><AndTogether>false</AndTogether></PromotionRuleBase></ArrayOfPromotionRuleBase>'
where PromotionDiscountData = '<ArrayOfPromotionRuleBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><PromotionRuleBase xsi:type="StartDatePromotionRule"><StartDate>2013-11-18T00:00:00</StartDate></PromotionRuleBase><PromotionRuleBase xsi:type="ExpirationDatePromotionRule"><ExpirationDate>2014-01-12T00:00:00</ExpirationDate></PromotionRuleBase><PromotionRuleBase xsi:type="ExpirationNumberOfUsesPerCustomerPromotionRule"><NumberOfUsesAllowed>1</NumberOfUsesAllowed></PromotionRuleBase><PromotionRuleBase xsi:type="ProductIdPromotionRule"><ProductIds><int>55232</int></ProductIds><RequireQuantity>false</RequireQuantity><Quantity>1</Quantity><AndTogether>false</AndTogether></PromotionRuleBase></ArrayOfPromotionRuleBase>'
but getting this error
Msg 402, Level 16, State 1, Line 1
The data types xml and varchar are incompatible in the equal to operator.
any idea how to fix this?
Basically within each cell I am trying to change the StartDate only
I suppose the type of PromotionDiscountData column is XML, so that's why I suggest you to use the following code snippet:
update Promotions
set PromotionDiscountData = '<ArrayOfPromotionRuleBase ...'
where CAST(PromotionDiscountData as NVARCHAR(MAX)) = '<ArrayOfPromotionRuleBase...'