SQL Server - Convert table data to xml - sql-server

Hi I have the following table data I need to convert to Xml in SQl Server. Any ideas?
Thanks in advance
From
Party_Id HomePhoneNumber WorkPhoneNumber
62356 6314993578
62356 6314590922
62356 6313795488
To
<HomePhoneNumber>6314993578</HomePhoneNumber>
<WorkPhoneNumber>6314590922</WorkPhoneNumber>
<WorkPhoneNumber>6313795488</WorkPhoneNumber>

Convert the empty values into NULLs. These NULL values will be excluded from the XML.
Declare #YourTable table (Party_Id int,HomePhoneNumber varchar(25),WorkPhoneNumber varchar(25))
Insert Into #YourTable values
(62356,'6314993578',''),
(62356,'','6314590922'),
(62356,'','6313795488')
Select HomePhoneNumber=case when HomePhoneNumber='' then null else HomePhoneNumber end
,WorkPhoneNumber=case when WorkPhoneNumber='' then null else WorkPhoneNumber end
From #YourTable
For XML Path('')
Returns
<HomePhoneNumber>6314993578</HomePhoneNumber>
<WorkPhoneNumber>6314590922</WorkPhoneNumber>
<WorkPhoneNumber>6313795488</WorkPhoneNumber>

Related

What is the purpose of XMLNAMESPACES in a CTE query on the SSRS database? [duplicate]

I tryng to read xml file in sql server:
DECLARE #XMLToParse XML
-- Load the XML data in to a variable to work with.
-- This would typically be passed as a parameter to a stored proc
SET #XMLToParse = '<Response xmlns="http://tempuri.org/">
<AuthResult xmlns:a="http://schemas.datacontract.org/2004/07/Sistema.Soap.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Result>
<a:Id_Value>500</a:Id_Value>
</a:Result>
<a:Result>
<a:Id_Value>895</a:Id_Value>
</a:Result>
</AuthResult>
</Response>'
-- Declare temp table to parse data into
DECLARE #ParsingTable TABLE
(Id_Value INT)
-- Parse the XML in to the temp table declared above
INSERT
INTO #ParsingTable
(Id_Value)
SELECT xmlData.A.value('.', 'INT') AS Id_Value
FROM #XMLToParse.nodes('Response/AuthResult/Result') xmlData(A)
-- Insert into the actual table from the temp table
SELECT Id_Value
FROM #ParsingTable
Apparently the code is correct but I can not get the values, where can I be wrong?
Use WITH XMLNAMESPACES to declare the namespaces and use the respective prefix for nodes not in the default namespace.
...
-- Parse the XML in to the temp table declared above
;WITH XMLNAMESPACES (DEFAULT 'http://tempuri.org/',
'http://schemas.datacontract.org/2004/07/Sistema.Soap.Contracts' as a,
'http://www.w3.org/2001/XMLSchema-instance' as i
)
INSERT
INTO #ParsingTable
(Id_Value)
SELECT xmlData.A.value('.', 'INT') AS Id_Value
FROM #XMLToParse.nodes('Response/AuthResult/a:Result') xmlData(A)
...

SQL Server : conversion error when attempting to load 'smallmoney' data into table

I'm trying to load a CSV file into a table in order to sort the data. However, the smallmoney column BillingRate (e.g. $203.75) will not convert, with SQL Server producing the following message:
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 2, column 4 (BillingRate).
Msg 4864, Level 16, State 1, Line 10
Here is the code I am using in order to do this:
--CREATE TABLE SubData2
--(
--RecordID int,
--SubscriberID int,
--BillingMonth int,
--BillingRate smallmoney,
--Region varchar(255)
--);
BULK INSERT Subdata2
FROM 'C:\Folder\1-caseint.csv'
WITH
(FIRSTROW = 2,
FIELDTERMINATOR = '|', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'C:\Folder\CaseErrorRows4.csv',
TABLOCK);
A typical line of code in the CSV files looks like:
1|0000000001|1|$233.94|"West"
Apologies if there are any glaring errors here - I'm new to SQL Server :)
Many thanks in advance,
Tom.
This is odd. On a direct insert only the last fails.
declare #t table (sm smallmoney);
insert into #t
values ('$256.6')
insert into #t
values (244.8);
insert into #t
values ('12.8');
insert into #t
values ('$256.5'), ('244.7');
insert into #t
values ($256.5);
insert into #t
values ('$256.5'), (244.7), ('12.12');
select * from #t;
Give it a try removing the $ from the data.

Finding a string in XML column using sql server

I have a table with a xml column.
I require to search for sub string in that xml column for all its node and value. Search should be case insensitive
Structure of XML in each row is different
I used below query to do that,
select * from TableName Where Cast(xmlcolumn as varchar(max) ) like '%searchString%'
this works for short length xml rows, if row length goes huge it cant handle the situation. Only partial of the data was searched.
Suggest me some other ways to achieve.
If this is one time task then I would use exist XML method thus:
DECLARE #Table1 TABLE (
ID INT IDENTITY PRIMARY KEY,
CommentAsXML XML
)
INSERT #Table1 (CommentAsXML)
VALUES (N'<root><item /><item type="Reg">0001</item><item type="Inv">B007</item><item type="Cus">A0001</item><item type="Br">F0001</item></root>')
INSERT #Table1 (CommentAsXML)
VALUES (N'<root><item /><item type="Reg">0005</item><parent><child>B007</child></parent><item type="Br">F0005</item></root>')
INSERT #Table1 (CommentAsXML)
VALUES (N'<root><item /><item type="Reg">0005</item></root>')
-- Following query is searching for B007 within InnerText of all XML elements:
SELECT *
FROM #Table1 t
WHERE t.CommentAsXML.exist('//*[lower-case(text()[1]) eq "b007"]') = 1
Results:
ID CommentAsXML
-- ------------------------------------------------------------------------------------------------------------------------------
1 <root><item type="Reg">0001</item><item type="Inv">B007</item><item type="Cus">A0001</item><item type="Br">F0001</item></root>
2 <root><item type="Reg">0005</item><parent><child>B007</child></parent><item type="Br">F0005</item></root>
Also, if you want to search for some text in XML atrributes' values then following XQuery could be used:
SELECT *
FROM #Table1 t
WHERE t.CommentAsXML.exist('//#*[lower-case(.) eq "reg"]') = 1
Note: in both cases, string constants (ex. "reg") should be with lower cases.

Generation of XML with list of integers in T-SQL?

I have an ID table. Right now I just need to generate a XML file as the following format. Actually, it is a list of integers.
--Target format
<ListOfIntegers>
<Integer>150356</Integer>
<Integer>150365</Integer>
</ListOfIntegers>
I tried to use this and many other ways,
SELECT #tempXML = ( SELECT ID AS [Integer]
FROM #tempIDTable
FOR XML PATH('ListOfIntegers'), ELEMENTS)
But it will only generate a XML file like
--Current format
<ListOfIntegers>
<Integer>150356</Integer>
</ListOfIntegers>
<ListOfIntegers>
<Integer>150365</Integer>
</ListOfIntegers>
What should I do?
You were quite close:
CREATE TABLE #tempIDTable(ID INT);
INSERT INTO #tempIDTable VALUES(1),(2),(3);
DECLARE #tempXML XML;
SELECT #tempXML = ( SELECT ID AS [Integer]
FROM #tempIDTable
FOR XML PATH(''),ROOT('ListOfIntegers'));
SELECT #tempXML;
DROP TABLE #tempIDTable;
The result:
<ListOfIntegers>
<Integer>1</Integer>
<Integer>2</Integer>
<Integer>3</Integer>
</ListOfIntegers>

Converting nvarchar to numeric

I have variable called #prmclientcode which is nvarchar. The input to this variable can be a single client code or multiple client codes separated by comma. For e.g.
#prmclientcode='1'
or
#prmclientcode='1,2,3'.
I am comparing this variable to a client code column in of the tables. The data type of this column is numeric(6,0). I tried converting the variable data type like below
SNCA_CLIENT_CODE IN ('''+convert(numeric(6,0),#prmclientcode+''')) (The query is inside a dynamic sql).
But when I try executing this I get the error
Arithmetic overflow error converting nvarchar to data type numeric.
Can anyone please help me here!
Thanks!
You need to convert the numeric(6,0) column to nvarchar data type. You can use below scrip to convert it to nvarchar, before processing:
SNCA_CLIENT_CODE IN ('''+convert(cast( numeric(6,0) as nvarchar(max) ),#prmclientcode+'''))
Please try with the below code snippet.
DECLARE #ProductTotals TABLE
(
ProductID int
)
INSERT INTO #ProductTotals VALUES(1)
INSERT INTO #ProductTotals VALUES(11)
INSERT INTO #ProductTotals VALUES(3)
DECLARE #prmclientcode VARCHAR(MAX)='1'
SELECT * FROM #ProductTotals
SELECT * FROM #ProductTotals WHERE CHARINDEX(',' + CAST(ProductID AS VARCHAR(MAX)) + ',' , ',' + ISNULL(#prmclientcode,ProductID) + ',') > 0
Let me know if any concern.
use following code in order to separate your variable:
DECLARE
#T VARCHAR(100) = '1,2,3,23,342',
#I int = 1
;WITH x(I, num) AS (
SELECT 1, CHARINDEX(',',#T,#I)
UNION ALL
SELECT num+1,CHARINDEX(',',#T,num+1)
FROM x
WHERE num+1<LEN(#T)
AND num<>0
)
SELECT SUBSTRING(#T,I,CASE WHEN num=0 THEN LEN(#T)+1 ELSE num END -I)
FROM x
Use can use either table function or dynamic sql query, both options will work.
Let me know if you need more help

Resources