obtain data from table 2 using reference of table 1 [sql-server] - sql

[TRN_ID] is the id of another table, how to get the data from that table and show this data in the xml output
SELECT TOP (1) [ECB_ID] as Id
,[ECB_PASSWORD_GENERATED] as clave
,[ECB_CONSECUTIVE_NUMBER] as consecutive
,[ECB_BILL_DATE] as date
,[TRN_ID] <- id of other table
,[QRC_ID]
FROM [crdx_COREDev1].[dbo].[ECB_ELECTRONICBILL]
FOR XML PATH ('FE')
example of output
<FE>
<id>1</id>
<pass>0</pass>
<CONSECUTIVE>0</CONSECUTIVE>
....
--These are the data from the other table.
<emisor>
<name>1</name>
<Copany>myCompa</Company>
...
...
</emisor>
</FE>
In summary, I have a table 1 with different data, some of those data are references to other tables, using that reference I want to obtain the data from table 2

You can use a nested FOR XML linked to your TRN_ID.
SELECT TOP (1)
[ECB_ID] as Id,
[ECB_PASSWORD_GENERATED] as clave,
[ECB_CONSECUTIVE_NUMBER] as consecutive,
[ECB_BILL_DATE] as date,
[TRN_ID],
[QRC_ID],
(
SELECT
N.YourWantedColumn
FROM
YourOtherTable AS N
WHERE
E.TRN_ID = N.TRN_ID -- I'm guessing it's called N.TRN_ID
FOR XML
PATH ('emisor'), TYPE
)
FROM
[crdx_COREDev1].[dbo].[ECB_ELECTRONICBILL] AS E
FOR XML
PATH ('FE')

Related

Postgresql JSON column check value exists in array of json

I have a database schema like the following where I have a Children record table
CREATE TABLE Children (
name varchar(100),
friends JSON NOT NULL,
);
INSERT INTO Children (name,friends)
VALUES('Sam',
array['{"name":"Rakesh","country":"Africa"}',
'{"name":"Ramesh","country":"India"}']::json[]);
Now I need to query the data and display it only if the name of the friend is like '%Ra'. Structure of the JSON data is consistent.
If you have json[] as data type then you can use unnest and then write your query, or if it is json then you can use json_array_elements.
Below code considers json[] data type -
select * from Children
where name in (
select name from (
select name, unnest(friends) as friend from Children
) i
where i.friend->>'name' like '%Ra');
DBFiddle

sql conversion script

I have a 2 databases that I want to merge with some similiar tables. The source tables have id as bigint and my destination table has int as ID. There aren't that many records in my source table (< 20k) so I want to assign new ids to all records so the ids can fit in an int. How can I do this with sql?
First Option
You can Use Sequence object as follow:
First Create a Sequence object and assign it's Start With value to max Id value in destination table plus 1. For example if max Id in destination table is 100, you need to assign 101 as Start With. You can also obtain the max Id value from destination table using a Max(Id) aggregate function and store it in a variable:
CREATE SEQUENCE SeqId
START WITH [Max value of Id in destination table]
INCREMENT BY 1 ;
GO
Then insert to destination table using following query:
Insert Into tblXXX (Id, ...) Values (NEXT VALUE FOR SeqId, ...)
Read more about Sequence Object
Second Option
You can make the destination table's Id column as Identity column with seed equal to destination table's Id column max value and Increment equal to 1.
Here is detailed example also Here
You did not provide much details so I can only provide a general guideline:
Note: Example assumes that you want to merge tables A and B into C and you want to generate new IDs. I also assume that these IDs are not referenced by other tables (foreign keys).
First you get record counts from tables A and B:
DECLARE #countA INT
DECLARE #countB INT
SET #countA = ( SELECT COUNT(*) FROM A )
SET #countB = ( SELECT COUNT(*) FROM B )
Next you use a window function to generate new IDs and insert records into table C.
INSERT INTO C
SELECT #countA + ROW_NUMBER() OVER( ORDER BY ID ) AS ID, ....
FROM A
INSERT INTO C
SELECT #countA + #countB + ROW_NUMBER() OVER( ORDER BY ID ) AS ID, ....
FROM B

Extract data matching a condition inside an XML array in SQL server

Considering this simple table id (int), name (varchar), customFields (xml)
customFields contains an XML representation of a C# Dictionary. E.g :
<dictionary>
<item>
<key><int>1</int></key>
<value><string>Audi</string></value>
</item>
<item>
<key><int>2</int></key>
<value><string>Red</string></value>
</item>
</dictionary>
How do I select all rows of my table with 3 columns: id, name and 1 column that is the content of the string tag where the value of the int tag is equal 1.
The closest to the result I managed to get is:
SELECT id, name, C.value('(value/string/text())[1]', 'varchar(max)')
FROM myTable
OUTER APPLY customFields.nodes('/dictionary/item') N(C)
WHERE (customFields IS NULL OR C.value('(key/int/text())[1]', 'int') = 1)
Problem is, if xml doesn't have a int tag = 1 the row is not returned at all (I would still like to get a row with id, name and NULL in the 3rd column)
I've created a table the same as yours and this query worked fine:
select id, name,
(select C.value('(value/string/text())[1]','varchar(MAX)')
from xmlTable inr outer apply
customField.nodes('/dictionary/item') N(C)
where
C.value('(key/int/text())[1]','int') = 1
and inr.id = ou.id) as xmlVal
from xmlTable ou
Here is my result:
The reason why your query didn't worked is because it first selects values of "value/string" for all rows from "myTable" and then filters them. Therefore, the null values appear only on empty fields, and on the other fields (which contains any xml value), the "value/string/text()" is displayed. This is what your query without where clause returns:
id,name,xml
1 lol NULL
2 rotfl Audi
2 rotfl Red
3 troll Red

how to extract data from xml having multiple nodes which are same under a parent node into a table in sql

I have a xml like
<list of roleids>
<roleid> 1 </roleid>
<roleid> 2 </roleid>
<roleid> 3 </roleid>
<roleid> 4 </roleid>
</list of Roleids>
I want the roleid values in a table with column RoleID
I have tried with the below query but i am not getting the expected output
declare #ListOfRoleID XML
set #ListOfRoleID =
'<list>
<roleid>1</roleid>
<roleid>2</roleid>
</list>'
DECLARE #RoleIDList TABLE (RoleID int)
INSERT INTO #RoleIDList(RoleID)
SELECT X1.value('(roleid)[1]','INT') as roleid
from #ListOfRoleID.nodes('/list') as ListOfRoleID(x)
CROSS APPLY #RoleIDList.nodes('/list') AS ListOfRoleID1 (X1)
You want to project .nodes('/list/roleid'), which will create one row per roleid. Then extract the value. No need for cross apply. See sqlfiddle:
declare #ListOfRoleID XML = '<list>
<roleid>1</roleid>
<roleid>2</roleid>
<roleid>3</roleid>
</list>';
SELECT x.value('.','INT') as roleid
from #ListOfRoleID.nodes('/list/roleid') as ListOfRoleID(x);

delete all the child rows in sql table by parentid

I have a table from which I create a tree with multiple levels and parents. The table structure looks like this.
When I delete the "TitleID", I want all the children and even the grandchildren to be deleted.
What is the easiest way to do such in sql.
If I simple delete with "where ParentID=TitleID", only children with level 1 depth are deleted.
DECLARE #TitleId INT
SELECT ##TitleId = 2
;WITH results AS(
SELECT TitleId
FROM myTable
WHERE TitleId = #TitleId
UNION ALL
SELECT t.TitleId
FROM myTable t
INNER JOIN ret r ON t.ParentID = r.TitleId
)
DELETE FROM myTable WHERE TitleId IN (SELECT TitleId FROM results )
To handle tree structured data in relational database, you can add another column FullID, which contains value like 1.1.3. Then what you need is just a simple where clause WHERE FullID LIKE '1.1.%' if you want to delete node 1.1 and it's children.
The value of FullID can be generated by a stored procedure (for old data), or better by your application (for new data).