Is there a simple way to create an XML (file, variable, value in column, whatever) with select * from table for xml ...
and later automatically insert this data into identical table in different database? Something like insert into table from xml ...
. All solutions I can find require providing column names explicitly.
What I want in the end is a simple thing – I have Java service connecting to the database. It is able to download new dictionary data and insert (merge) it into specific tables. Currently there are quite a few such tables and we have separate procedures for them, all specifying columns names and so on. This is getting out of hand and I'm looking for some way of simplifying it.
Best Answer
Here is what I ended with.
Assuming that data is read from the table using the following:
I get this data from one server and store it as a tuple (schema, table, keys, xml), where:
schema
is schema name (e.g.dbo
)table
is table name (e.g.someTable
)keys
is comma-separated list of "keys" (columns used for<match>
inmerge ... on <match>
, e.g.st_id
in example above, if there are more keys they should bepassed,like,this
)xml
is data as an xml (easy)This data is then passed to some other server, where there is one function and one procedure defined.
Function
tools.GenerateXMLMergerForTable
creates body (whole declaration in fact) of procedure used for merging data read fromxml
into tabletable
in schemaschema
using parsed stringkeys
as<match>
.Procedure
tools.createXMLMergerForTable
executes aforementioned function and creates procedure that takes single parameter (of type XML) and merges data read from it into table that it was configured for.T-SQL follows:
Java code simply reads tuple defined above, inserts parameters that it knows off, creates random suffix, creates merging procedure, executes it using
xml
from The Tuple and drops previously created procedure.It seems to work as advertised, though no guarantees are provided.
NOTE: it is assumed that function, procedure and subsequently created procedures live in schema
tools
.NOTE 2: It is possible that you will get information about
string_split
object not found, if so then just do:For reasons see documentation of string_split and how to change compatibility level.