cast text to xml error illegal qualified name character - sql

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.

Related

Handle XML data that is in single quote while loading

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)

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.

How to solve incorrect syntax near 'xml'?

I'm working on an administration program, and when writing one of it's features I encountered this error.
Here's the code.
CODE:
create procedure wIaTertiDemo
#sesiune varchar(50),
parXML xml
as
begin try
declare #utilizator varchar(500)
exec wIaUtilizator #sesiune #utilizator output
select codfiscal, denumire as #dentert, adresa
from tertiDemo
for xml raw
--create table tertiDemo(codfiscal varchar(50), denumire varchar(500), adresa varchar(500)
end try
BEGIN CATCH
DECLARE #mesajEroare varchar(1000)
SET #mesajEroare = ERROR_MESSAGE()+ '(' +OBJECT_NAME(##PROCID) + ')'
RAISERROR (#mesajEroare, 16,1)
END CATCH
Errors:
Msg 102, Level 15, State 1, Procedure wIaTertiDemo, Line 1 [Batch Start Line 0]
Incorrect syntax near 'xml'
Msg 102, Level 15, State 1, Procedure wIaTertiDemo, Line 6 [Batch Start Line 0]
Incorrect syntax near '#utilizator'
Msg 102, Level 15, State 1, Procedure wIaTertiDemo, Line 8 [Batch Start Line 0]
Incorrect syntax near '#dentert'
parXML xml
Should be:
#parXML xml
And
exec wIaUtilizator #sesiune #utilizator output
should be:
exec wIaUtilizator #sesiune, #utilizator output
And
denumire as #dentert
should be:
denumire as dentert

Escaping characters in T-SQL OPENJSON queries

I have the following JSON Data
DECLARE #jsonData NVARCHAR(MAX)
SET #jsonData =
'{
"insertions":[
{
"id":"58735A79-DEA8-462B-B3EB-C2797CA9D44E",
"last-modified":"2017-08-08 13:07:32",
"label":"HelloWorld1"
},
{
"id":"00565BCD-4240-46CF-A48F-849CB5A8114F",
"last-modified":"2017-08-08 13:11:38",
"label":"HelloWorld12"
}
]
}'
And trying to perform a select from it:
SELECT
*
FROM
OPENJSON(JSON_QUERY(#jsonData,'$.insertions'))
WITH
(uuid UNIQUEIDENTIFIER '$.id',
modified DATETIME '$.last-modified',
Label NVARCHAR(128) '$.label'
)
It doesn't like the dash in the last-modified field.
Msg 13607, Level 16, State 4, Line 18
JSON path is not properly formatted. Unexpected character '-' is found at position 6.
Is there a way to escape the dash in the query? Everything works fine if there is no dash.
As required to support JSON, I'm using SQL Server 2016 with compatibility level = 130
Adding double quotes around the field name seems to work
SELECT
*
FROM
OPENJSON(JSON_QUERY(#jsonData,'$.insertions'))
WITH
(uuid UNIQUEIDENTIFIER '$.id',
modified DATETIME '$."last-modified"',
Label NVARCHAR(128) '$.label'
)

Msg 8115, Level 16, State 6, Line 4 Arithmetic overflow error converting varchar to data type numeric

This is the query I have written.
DECLARE #SQL_BULK VARCHAR(MAX)
declare #cp decimal(14,2)=1000
declare #tb varchar(20)='tbl_LT'
set #SQL_BULK='insert into '+#tb+'(ClosePrice) values('''+#cp+''');'
EXEC (#SQL_BULK)
When I execute the query I am getting Msg 8115, Level 16, State 6, Line 4
Arithmetic overflow error converting varchar to data type numeric. as error.
I have tried cast, conversion methods.
The + operator is overloaded in SQL Server. If any argument is numeric, then it is a string.
Often, I do what you want to do using replace() to prevent this problem:
set #SQL_BULK = 'insert into #tb(ClosePrice) values(#cp)';
set #SQL_BULK = replace(#SQL_BULK, '#tb', #tb);
set #SQL_BULK = replace(#SQL_BULK, '#cp', #cb);
EXEC (#SQL_BULK)
As a note: you should probably use `sp_executesql and pass in the second value as a parameter:
set #SQL_BULK = 'insert into #tb(ClosePrice) values(''#cp'')';
set #SQL_BULK = replace(#SQL_BULK, '#tb', #tb);
exec sp_executesql #SQL_BULK, N'#cb decimal(14, 2)', #cp = #cp;
Whenever you add Numerics to a string, the default behavior is to convert the string to Number.
In this case
set #SQL_BULK='insert into '+#tb+'(ClosePrice) values('''+#cp+''');'
you are adding #cp to a string which is causing the problem.
You have to re-write this as
set #SQL_BULK='insert into '+#tb+'(ClosePrice) values('''+CAST(#cp AS VARCHAR)+''');'