I try to check my data bad if a table is existing and get the print output from my statement as XML
For that I tried following code:
IF (
EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'TABLE_NAME_I'
)
) BEGIN
PRINT 'Table allready exists in database'
FOR XML AUTO
END;
But the only thing I gat is:
Database operation failed: Incorrect syntax near the FOR keyword.
I also tried to set the FOR XML AUTO
in front of PRINT 'Table allready exists in database'
but the resault is the same.
I'm using an JDBC Connector to realize the connection and the output.
Is my project possible at all or do I have to combine it with something else to achieve this?
Thanks in advance for the help.
UPDATE
SET @string = '<MESSAGE>Table allready exists in database</MESSAGE>';
SET @xml = CONVERT(XML, @string);
SELECT @xml;
Here is my output which I get:
<Data>
<object_II>
<_1/>
</object_II>
<Data>
Expected output:
<Data>
<object_II>
<MESSAGE>Table allready exists in database</MESSAGE>
</object_II>
<Data>
You can try XQuery and FLWOR expression to compose desired XML.
SQL
DECLARE @message VARCHAR(100) = 'Table allready exists in database';
SELECT CAST(N'' AS XML).query('
<Data>
<object_II>
<MESSAGE>{sql:variable("@message")}</MESSAGE>
</object_II>
</Data>
');
Or completely dynamic XML composition:
SELECT CAST(N'' AS XML).query('
element Data {
element object_II {
element MESSAGE {
text {sql:variable("@message")}
}
}
}
');