I want to store data from multiple tables into one table
table A (
p, q,
PRIMARY KEY (p,q)
)
table B (
p, m, n,
PRIMARY KEY (p,m,n)
)
table output(
p,
xml
)
The output should be like
for table A
-------------------------------
| p | xml |
---------------------------------
|value of p | <q>some value</q> |
-------------------------------
for table B
-----------------------------------------------
| p | xml |
------------------------------------------------
|value of p | <m>some value</m><n>some data</n> |
-----------------------------------------------
This can be achieved by this query
SELECT *
FROM Students s
CROSS APPLY
(
SELECT
(
SELECT *
FROM Students t
WHERE t.DisplayName = s.DisplayName
FOR XML RAW
) x1
)x
But I want to make the SQL generic enough so that given any table name we can get the above output.
The problem with the inner join is that then the query will not be generic
To get the result you want from one table you could use something like this:
To apply the same pattern to another table you need to change the table name and the field name of the key column.
If you want a even more generic version you can use dynamic SQL and build your query from a table name and a column name.