Turning an XML into a select - sql

I'm trying to turn this XML string into a select
I have #Schedule XML = '<days><day enabled="0">0</day><day enabled="1">1</day><day enabled="1">2</day><day enabled="1">3</day><day enabled="1">4</day><day enabled="1">5</day><day enabled="0">6</day></days>'
What I'm trying to see at the end is..
DayNumber DayEnabled
0 0
1 1
2 1
3 1
4 1
5 1
6 0
I've tried a few ways, so far nothing is working right.. I am handling this as an XML data type, I'd prefer not to use a function as this will just be in a stored procedure..
Update: Maybe I didn't explain it correctly..
I have a stored procedure, XML is one of the parameters passed to it, I need to send it to a table to be inserted, so I'm trying to do the following..
INSERT INTO tblDays (DayNumber, DayEnabled)
SELECT #XMLParsedOrTempTableWithResults
I just can't figure out how to parsed the parameter

DECLARE #myXML as XML = '<days><day enabled="0">0</day><day enabled="1">1</day><day enabled="1">2</day><day enabled="1">3</day><day enabled="1">4</day><day enabled="1">5</day><day enabled="0">6</day></days>'
DECLARE #XMLDataTable table
(
DayNumber int
,DayEnabled int
)
INSERT INTO #XMLDataTable
SELECT d.value('text()[1]','int') AS [DayNumber]
,d.value('(#enabled)[1]','int') AS [DayEnabled]
FROM #myXML.nodes('/days/*') ds(d)
SELECT * FROM #XMLDataTable
Refer:
http://beyondrelational.com/modules/2/blogs/28/posts/10279/xquery-labs-a-collection-of-xquery-sample-scripts.aspx

The XMLTABLE function is how most XML-enabled DBMSes shred an XML document into a relational result set.
This example uses DB2's syntax for XMLTABLE and an input parameter passed into a stored procedure:
INSERT INTO tblDays (DayNumber, DayEnabled)
SELECT X.* FROM
XMLTABLE ('$d/days/day' PASSING XMLPARSE( DOCUMENT SPinputParm ) as "d"
COLUMNS
dayNumber INTEGER PATH '.',
dayEnabled SMALLINT PATH '#enabled'
) AS X
;

Related

Scalar variable issue not being able to use in Select Query SQL Server

I 'm not able to use both Declare statements in my select query when I do the insert into.
How do you use a column itemId to be set in a another column called id?
How do you write a same string to a specific column?
Why can't I call my scalar variable ?
DECLARE #Solutions_id as INT
DECLARE #Solutions_name as nvarchar(50)
INSERT INTO ticket_historical_actions
(
[id]
,[type]
[Solutions _rowId]
,[Solutions_dw_dateCreate]
,[Solutions_dw_dateMod]
,[Solutions_dw_dateDelete]
,[Solutions_sourceId]
,[Solutions_date_create]
,[Solutions_date_mod]
,[Solutions_date_approval]
,[Solutions_itemId]
,[Solutions_solutionTypeName]
,[Solutions_content_plainText]
,[Solutions_userId]
,[Solutions_userId_editor]
,[Solutions_userId_approval]
,[Solutions_userName]
,[Solutions_userName_approval]
,[Solutions_status]
,[Ticket_rowId]
,[Ticket_dw_dateCreate]
,[Ticket_dw_dateMod]
,[Ticket_dw_dateDelete]
,[Ticket_sourceId]
,[Ticket_date_create]
,[Ticket_date_mod]
,[Ticket_date_close]
,[Ticket_date_solve]
,[Ticket_entityId]
,[Ticket_name]
,[Ticket_date]
,[Ticket_status]
,[Ticket_is_deleted]
,[Ticket_content_PlainText]
,[Ticket_type]
,[Ticket_urgency]
,[Ticket_impact]
,[Ticket_priority]
,[Ticket_requestTypeId]
,[Ticket_userId_lastUpdater]
,[Ticket_userId_recipient]
,[Ticket_time_to_resolve]
,[Ticket_time_to_own]
,[Users_rowId]
,[Users_dw_dateCreate]
,[Users_dw_dateMod]
,[Users_dw_dateDelete]
,[Users_sourceId]
,[Users_date_create]
,[Users_date_mod]
,[Users_name]
,[Users_LastName]
,[Users_firstName]
,[Users_phone]
,[Users_mobile]
,[Users_language]
,[Users_profileId]
,[Users_entitieId]
,[Users_titleId]
,[Users_categoryId]
,[Users_managerId]
,[Company_rowId]
, [Company_dw_dateCreate]
,[Company_dw_dateMod]
,[Company_dw_dateDelete]
,[Company_sourceId]
,[Company_date_mod]
,[Company_date_create]
,[Company_completename]
,[Company_name]
,[Company_address]
,[Company_postcode]
,[Company_town]
,[Company_state]
,[Company_country]
,[Company_phonenumber]
,[Company_email]
,[Company_admin_email]
,[Company_admin_name]
)
SELECT
#Solutions_id =[itemId], #Solutions_name = 'Solutions',
ts.[rowId]
,ts.[dw_dateCreate]
,ts.[dw_dateMod]
,ts.[dw_dateDelete]
,ts.[sourceId]
,ts.[date_create]
,ts.[date_mod]
,ts.[date_approval]
,ts.[itemId]
,ts.[solutionTypeName]
,ts.[content_plainText]
,ts.[userId]
,ts.[userId_editor]
,ts.[userId_approval]
,ts.[userName]
,ts.[userName_approval]
,ts.[status]
, tt. [rowId]
,tt.[dw_dateCreate]
,tt.[dw_dateMod]
,tt.[dw_dateDelete]
,tt.[sourceId]
,tt.[date_create]
,tt.[date_mod]
,tt.[date_close]
,tt.[date_solve]
,tt.[entityId]
,tt.[name]
,tt.[date]
,tt.[status]
,tt.[is_deleted]
,tt.[content_PlainText]
,tt.[type]
,tt.[urgency]
,tt.[impact]
,tt.[priority]
,tt.[requestTypeId]
,tt.[userId_lastUpdater]
,tt.[userId_recipient]
,tt.[time_to_resolve]
,tt.[time_to_own]
, tu.[rowId]
,tu.[dw_dateCreate]
,tu.[dw_dateMod]
,tu.[dw_dateDelete]
,tu.[sourceId]
,tu.[date_create]
,tu.[date_mod]
,tu.[name]
,tu.[LastName]
,tu.[firstName]
,tu.[phone]
,tu.[mobile]
,tu.[language]
,tu.[profileId]
,tu.[entitieId]
,tu.[titleId]
,tu.[categoryId]
,tu.[managerId]
, tc. [rowId]
,tc.[dw_dateCreate]
,tc.[dw_dateMod]
,tc.[dw_dateDelete]
,tc.[sourceId]
,tc.[date_mod]
,tc.[date_create]
,tc.[completename]
,tc.[name]
,tc.[address]
,tc.[postcode]
,tc.[town]
,tc.[state]
,tc.[country]
,tc.[phonenumber]
,tc.[email]
,tc.[admin_email]
,tc.[admin_name]
FROM
ticket_ticketSolutions ts
left join ticket_tickets tt
on ts.itemId =tt.sourceId
left join ticket_users tu
on ts.userId = tu.sourceId
left join ticket_company tc
on tu.entitieId = tc.sourceId
Would tell me if possible how to do it?
Thank you very much.
I'm just going to answer, even though I have stated this in the comments of both your questions.
The problem here is you are trying to assign a value to your variables in the same statement you are trying to return a dataset; in T-SQL that in not allowed.
In short, you have something like this:
SELECT #MyVariable = SomeColumn,
AnotherColumn
FROM dbo.YourTable
WHERE ID = 'SomeID';
So you want to return the value of AnotherColumn to the presentation layer, but assign the value of SomeColumn to the variable #MyVariable; you can't do this.
Instead, you have to use 2 statements:
SELECT #MyVariable = SomeColumn --Assigns the value to #MyVariable
FROM dbo.YourTable
WHERE ID = 'SomeID';
SELECT AnotherColumn --Returns the dataset to the presentation layer
FROM dbo.YourTable
WHERE ID = 'SomeID';

Get Values between Each Comma in Seperate Row in SQL Server

I need to insert multiple rows in a database table from a single string.
Here is my string it will be comma-seperated values
Current string:
batch 1 45665 987655,1228857 76554738,12390 8885858,301297 38998798
What I want is that batch 1 should be ignored or removed and remaining part should be added into the SQL Server database as a separate row for after each comma like this
Table name dbo.MSISDNData
Data
------------------
45665 987655
1228857 76554738
12390 8885858
301297 38998798
and when I query the table it should return the results like this
Query :
Select data
from dbo.MSISDNData
Results
Data
---------------------
45665 987655
1228857 76554738
12390 8885858
301297 38998798
Try this:
DECLARE #Data NVARCHAR(MAX) = N'batch 1 45665 987655,1228857 76554738,12390 8885858,301297 38998798'
DECLARE #DataXML XML;
SET #Data = '<a>' + REPLACE(REPLACE(#Data, 'batch 1 ', ''), ',', '</a><a>') + '</a>';
SET #DataXML = #Data;
SELECT LTRIM(RTRIM(T.c.value('.', 'VARCHAR(MAX)'))) AS [Data]
FROM #DataXML.nodes('./a') T(c);
It demonstrates how to split the data. You may need to sanitize it, too - remove the batch 1, perform trimming, etc.

How can I write this SQL while loop code to get an XML results in one line instead of 3 separate lines?

I'm trying to get all this XML result in one line instead of 3 for each column
DECLARE #ii INT = 10;
DECLARE #String1 NVARCHAR(4000);
SET #String1 = '';
WHILE(#ii <= 18)
BEGIN
SET #String1 = (#String1 + 'SELECT LoanNumber = ''Complaint'+CONVERT(VARCHAR(2),#ii)+'-Call1'' , LoanStatus=''Compliants'' , LoanStatusDate = CAST(GETDATE() AS DATE)
UNION
SELECT LoanNumber = ''Complaint'+CONVERT(VARCHAR(2),#ii)+'-Call2'', LoanStatus=''Compliants'' , LoanStatusDate = CAST(GETDATE() AS DATE)
UNION
SELECT LoanNumber = ''Complaint'+CONVERT(VARCHAR(2),#ii)+'-Call3'', LoanStatus=''Compliants'' , LoanStatusDate = CAST(GETDATE() AS DATE)')
IF #ii != 18
SET #string1 = #string1 + ' UNION '
ELSE
SET #string1 = #string1 + 'FOR XML PATH (''Loan''),ROOT(''Loans'') '
SET #ii = #ii+1
END
EXEC sp_executesql #String1
I want something like this:
<Loans>
<LoanNumber>Complaint10-Call1<LoanStatus>Compliants<LoanStatusDate>2019-01-18
</Loan>
<Loan>
<LoanNumber>Complaint10-Call2 <LoanStatus>Compliants<LoanStatusDate>2019-01-18
</Loan>
<Loan>
<LoanNumber>Complaint10-Call3<LoanStatus>Compliants<LoanStatusDate>2019-01-18
</Loan>
Instead of the result that you get when you execute the code I provided. I appreciate your help.
This might be wild guessing, but I've got the feeling, that I understand, what this is about:
if you run the code you will see the result. no input data is needed .
I just want the structure of the xml outcome to all be on one line for
one set of each loop
Your provided code leads to this:
<Loans>
<Loan>
<LoanNumber>Complaint10-Call1</LoanNumber>
<LoanStatus>Compliants</LoanStatus>
<LoanStatusDate>2019-01-22</LoanStatusDate>
</Loan>
<Loan>
<LoanNumber>Complaint10-Call2</LoanNumber>
<LoanStatus>Compliants</LoanStatus>
<LoanStatusDate>2019-01-22</LoanStatusDate>
</Loan>
<!-- more of them-->
</Loans>
This is perfectly okay, valid XML.
But you want the result
outcome to all be on one line for one set of each loop
Something like this?
<Loans>
<Loan>
<LoanNumber>Complaint10-Call1</LoanNumber><LoanStatus>Compliants</LoanStatus><LoanStatusDate>2019-01-22</LoanStatusDate>
</Loan>
<!-- more of them-->
</Loans>
There is a big misconception I think... XML is not the thing you see. The same XML can look quite differently, without any semantic difference:
Check this out:
DECLARE #xmltable table(SomeXml XML)
INSERT INTO #xmltable VALUES
--the whole in one line
('<root><a>test</a><a>test2</a></root>')
--all <a>s in one line
,('<root>
<a>test</a><a>test2</a>
</root>')
--each element in one line
,('<root>
<a>test</a>
<a>test2</a>
</root>')
--white space going wild...
,('<root>
<a>test</a>
<a>test2</a>
</root>');
--now check the results
SELECT * FROM #xmltable;
This means: How the XML appears is a matter of the interpreter. The same XML opened with another tool might appear differently. Dealing with XML means dealing with data but not with format... The actual format has no meaning and should not matter at all...
Starting with SQL-Server 2016 you might have a look at JSON, if you need a tiny format:
DECLARE #somedata table(SomeValue VARCHAR(100),SomeStatus VARCHAR(100),SomeDate DATE);
INSERT INTO #somedata VALUES
('Complaint10-Call1','Complaints','2019-01-22')
,('Complaint10-Call2','Complaints','2019-01-22')
,('Complaint10-Call3','Complaints','2019-01-22');
SELECT * FROM #somedata FOR JSON PATH;
The result comes in one line:
[{"SomeValue":"Complaint10-Call1","SomeStatus":"Complaints","SomeDate":"2019-01-22"},{"SomeValue":"Complaint10-Call2","SomeStatus":"Complaints","SomeDate":"2019-01-22"},{"SomeValue":"Complaint10-Call3","SomeStatus":"Complaints","SomeDate":"2019-01-22"}]

Leading 0 on int Column problem SQL Server

I have an issue where I am trying to add a leading 0 to run an output.
SELECT
CASE
WHEN LEN(t.trans_time) = 5
THEN CONCAT(0, [trans_time])
ELSE T.[trans_time]
END AS [TransactionTime]
,RIGHT(CONCAT(0,trans_time),6) AS trans_time
,LEN(T.trans_Time)
,t.trans_time
Why does the case statement not return the leading 0 whereas using:
,RIGHT(CONCAT(0,trans_time),6) AS trans_time
Works no problem.
Case expression return only one type, whereas concat() would return different type & i am assuming trans_time has INT type.
So, you would need to do type conversations :
SELECT (CASE WHEN LEN(t.trans_time) = 5
THEN CONCAT(0, [trans_time])
ELSE CAST(T.[trans_time] AS VARCHAR(255))
END) AS [TransactionTime],
. . .
Another way to do this is to use the format function, wich is available from sql server 2012.
It not only makes the code more readable but will also perform better.
declare #t table (id int)
insert into #t values (90113), (90204), (90207), (90235), (90302), (90318), (90324)
select format(id, '000000') as TransactionTime from #t
this will return
TransactionTime
---------------
090113
090204
090207
090235
090302
090318
090324

How to split a string in sql server using stored procedure and insert the data to table

<pre>update d
set d.Price = null
from dbo.SalDocumentDetail d
left join dbo.StkWarehouse w on w.WarehouseID = d.WarehouseID
where DocumentID=" + 1 + "
and DocumentTypeID=" + 2 + "
and FiscalYear= " + 2016 + "
and isnull(isPrescription,0) <>1
and w.POSType is null
and ProductName BETWEEN ''C' 'AND' 'M''
and Country LIKE ''%land%'''</pre>
Actually this string is only a sample one my original string is very large . i am not getting a point that if i break this string than how many variables i have to make to capture the data also after splitting the string i want that to be inserted into data table containing columns as Felid and Value?
I want my result like :
<pre>
Felid Value
DocumentID= 1
DocumentTypeID= 2
FiscalYear= 2016
isnull(isPrescription,0) <>= 1
w.POSType is= null
ProductName= C
ProductName= M
Country= land
</pre>
<pre>I Use this function but this function split 'and' not split like what i want in my result i want split 'and,or,like,is,between ' if function find any this split it to two columns (Felid and Value)</pre>
<pre>ALTER FUNCTION [dbo].[fnSplitString]
(#List NVARCHAR(MAX),#Delimiter NVARCHAR(255))
RETURNS #Items TABLE(Felid NVARCHAR(Max),Valu nvarchar(MAx))
WITH SCHEMABINDING
AS BEGIN
DECLARE #ll INT=LEN(#List)+1,#ld INT=LEN(#Delimiter);
WITH a AS
(SELECT
[end]=COALESCE(NULLIF(CHARINDEX(#Delimiter,#List,1),0),#ll),
[VlaueFelid]=SUBSTRING(#List,(select
CHARINDEX('where',#List)+5),COALESCE(NULLIF(CHARINDEX('=', #List,0),0),#ll) ) ,
[Value]=SUBSTRING(#List,(select CHARINDEX('="',#List)+2),(select CHARINDEX('and',#List))-(select C`enter code here`HARINDEX('="',#List)+3))
UNION ALL
SELECT
[end]=COALESCE(NULLIF(CHARINDEX(#Delimiter,#List,[end]+#ld), 0),#ll),
[VlaueFelid]=SUBSTRING(#List,[end]+#ld, COALESCE(NULLIF(CHARINDEX('=',#List, [end]+#ld),0),#ll)-[end]-#ld),
[Value]=SUBSTRING(#List,[end]+#ld+16, COALESCE(NULLIF(CHARINDEX('=',#List,[end]+#ld),0),#ll)-[end]-#ld-5)
FROM a WHERE [end]< #ll) INSERT #Items SELECT[VlaueFelid],[Value] FROM a WHERE LEN([VlaueFelid])>0 RETURN;
END</pre>