Save the xml result to a column in a SQL table - html

I have copied the code somewhere in the internet and have created an html table using something like
''FOR XML RAW (''TR''), ELEMENTS, TYPE) AS ''TBODY''',
' FOR XML PATH (''''), ROOT (''TABLE'')'`
in SQL. The result is as expected which is an HTML table, below is the snippet.
Can someone point me on how to get the HTML string and save it into a column in my table. My thought was to get the result and save it as a string then insert it into a column in my table but after sometimes I failed.
The code example can be retrieve from https://www.mssqltips.com/sqlservertip/5025/stored-procedure-to-generate-html-tables-for-sql-server-query-output/

Cheers!! it's simple but I went around the globe. What I did was adding SET #Myvariable = in the dynamic query. Previously, I have tried so hard to assign the result into a variable outside the dynamic query which will never work for me.
Originally:
SET #DynTSQL = CONCAT (
'SELECT (SELECT '
, #columnslist
,' '
, #restOfQuery
,' FOR XML RAW (''TR''), ELEMENTS, TYPE) AS ''TBODY'''
,' FOR XML PATH (''''), ROOT (''TABLE'')'
)
What I did:
SET #DynTSQL = 'SET #SQLQuery1 =('+CONCAT (
'SELECT (SELECT '
, #columnslist
,' '
, #restOfQuery
,' FOR XML RAW (''TR''), ELEMENTS, TYPE) AS ''TBODY'''
,' FOR XML PATH (''''), ROOT (''TABLE'')'
)+')'
The result will be assigned into the #SQLQuery1.
Cheers!!!

Related

Extracting a substring after finding a different substring

I've been playing around with Substring, left, right, charindex and can't quite get this to work
If this is the value in column name 'Data' (this is all one line)
{"email":{"RecipientId":"usertest","RecipientEmail":"test#test.com","Subject":"This is a test subject heading","RecipientSubject":"A recipient subject"}}
How do I do a SELECT statement to find the 'Subject' heading and then get the data 'This is a test subject'? The Subject value is different for every record so I just can't look for 'This is a test subject'.
So the end result should be This is a test subject for that SELECT result
The following query should do what you want:
declare #string varchar(max);
set #string = '{"email":{"RecipientId":"usertest","RecipientEmail":"test#test.com","Subject":"This is a test subject heading","RecipientSubject":"A recipient subject"}}';
select substring(#string,charindex('"Subject":',#string)+11,charindex('"RecipientSubject"',#string)-charindex('"Subject"',#string)-13);
The plain and easy-cheesy approach is this:
SELECT SUBSTRING(
t.YourString
,A.StartPosition
,CHARINDEX('"'
,t.YourString
,A.StartPosition+1) - A.StartPosition
)
FROM #dummyTable t
CROSS APPLY(SELECT CHARINDEX('"Subject":"',t.YourString)+11) A(StartPosition)
I use APPLY to calculate a value and use it like you'd use a variable. The idea is: Find the starting point and look for the closing quote from there. But this will break, whenever the content includes an (escaped) quote like in
"Subject":"This is \"quoted\" internally"
A more generic approach
Starting with v2016 JSON-support was introduced. With this (or a higher) version this is really simple:
Use this mockup-table for testing
DECLARE #dummyTable TABLE (YourString VARCHAR(1000));
INSERT INTO #dummyTable VALUES('{"email":{"RecipientId":"usertest","RecipientEmail":"test#test.com","Subject":"This is a test subject heading","RecipientSubject":"A recipient subject"}}');
--The OPENJSON-method will read this for you:
SELECT JsonContent.*
FROM #dummyTable t
CROSS APPLY OPENJSON(t.YourString,'$.email')
WITH(RecipientId VARCHAR(100)
,RecipientEmail VARCHAR(100)
,[Subject] VARCHAR(100)
,RecipientSubject VARCHAR(100)) JsonContent;
But with a lower version you will need to trick this out. It is the easiest, to tranform JSON to attribute centered XML like here:
<email RecipientId="usertest" RecipientEmail="test#test.com" Subject="This is a test subject heading" RecipientSubject="A recipient subject" />
We can achieve this by some string methods and I must warn you, that there are several pit-falls with forbidden characters and other stuff... Just try it out:
SELECT Casted.ToXml.value('(/email/#RecipientId)[1]','varchar(1000)') AS RecipientId
,Casted.ToXml.value('(/email/#RecipientEmail)[1]','varchar(1000)') AS RecipientEmail
,Casted.ToXml.value('(/email/#Subject)[1]','varchar(1000)') AS [Subject]
,Casted.ToXml.value('(/email/#RecipientSubject)[1]','varchar(1000)') AS RecipientSubject
,Casted.ToXml.query('.') LookHowThisWasTransformed
FROM #dummyTable t
CROSS APPLY
(
SELECT CAST(CONCAT('<email '
,REPLACE(REPLACE(REPLACE(REPLACE(t.YourString,'{"email":{"',''),'}}',''),'","','" '),'":"',' ="')
,' />') AS XML)
) Casted(ToXml);

Using the trim function to narrow down results set

I need to gather data from two columns, concat them so that it's only the first six of the first column and the last six of the second column, separated by ' + '. Some have been input with weird spaces in front or in back, so we must also use the trim feature and get rid of all NULL. I haven't had any issues with the first part, but am struggling to use the trim feature in a way that gives the desired output.
Output needs to look like this:
Input Data sample:
The following code returns results, but the output doesn't match so I know the trim is wrong:
SELECT CONCAT(SUBSTRING(baseball, 1, 6), ' + ',
SUBSTRING(football, -6)) AS MYSTRING
FROM datenumtest2
WHERE baseball IS NOT NULL AND football IS NOT NULL;
I also tried the following, but get an error message about the parameters being incorrect:
SELECT CONCAT(SUBSTRING(LTRIM(baseball, 1, 6)), ' + ',
SUBSTRING(RTRIM(football, -6))) AS MYSTRING
FROM datenumtest2
WHERE baseball IS NOT NULL AND
football IS NOT NULL;
I'm still new to this site and learning, but I have tried to include as much as I can! If there is other information that I can add to help, please let me know.
You just need to use Trim() on the column(s), before using Substring() function on them:
SELECT CONCAT(SUBSTRING(TRIM(baseball), 1, 6), ' + ',
SUBSTRING(TRIM(football), -6)) AS MYSTRING
FROM datenumtest2
WHERE baseball IS NOT NULL AND
football IS NOT NULL;

Upload contents of CSV as new maximum stock position in Exact Online

I want to upload the contents of a CSV file as new values in Exact Online data set using for instance the following SQL statement:
update exactonlinerest..ItemWarehouses
set maximumstock=0
where id='06071a98-7c74-4c26-9dbe-1d422f533246'
and maximumstock != 0
I can retrieve the contents of the file using:
select *
from files('C:\path\SQLScripts', '*.csv', true)#os fle
join read_file_text(fle.file_path)#os
But seem unable to change the multi-line text in the file_contents field to separate lines or records.
How can I split the file_contents's field into multi lines (for instance using 'update ...' || VALUE and then running it through ##mydump.sql or directly using insert into / update statement)?
For now I've been able to solve it using regular expressions and then loading generated SQL statement into the SQL engine as follows:
select regexp_replace(rft.file_contents, '^([^,]*),([^,]*)(|,.*)$', 'update exactonlinerest..ItemWarehouses set maximumstock = $1 where code = $2 and maximumstock != $1;' || chr(13), 1, 0, 'm') stmts
, 'dump2.sql' filename
from files('C:\path\SQLScripts', '*.csv', true)#os fle
join read_file_text(fle.file_path)#os rft
local export documents in stmts to "c:\path\sqlscripts" filename column filename
#c:\hantex\path\dump2.sql
However, it is error prone when I have a single quote in the article code.

Exporting SQL Query Results to Text File From Microsoft Visual Studio

I've looked for the past hour online to find an answer specific to my situation, but none have solved my question. I am trying to query a MySQL database (which I have done successfully) and then output the results to a text file.
I have read that using bcp and "queryout" are the best methods of achieving this goal. My code is below, but it continues to give me the following errors: "Incorrect Syntax Near 'L'.".
How do I fix this? Is there an easier way to export my results from Visual Studio to a text file?
set #logtext =
'"
SELECT category, occurTime, sourceKeyName, recipe, "value", formulaName, startTime, endTime , BatchID
FROM dbo.Batch
LEFT JOIN dbo.BatchHeader ON Batch.uniqueBatchID = BatchHeader.uniqueBatchID
LEFT JOIN dbo.RecipeHeader ON BatchHeader.uniqueBatchID = RecipeHeader.uniqueBatchID
LEFT JOIN dbo.BReportEvent ON RecipeHeader.uniqueBatchID = BReportEvent.uniqueBatchID
LEFT JOIN dbo.RecipeFormula ON BReportEvent.uniqueBatchID = RecipeFormula.uniqueBatchID
WHERE category = 'L-FAIL-MSG'
AND occurTime >= DATEADD(day, -1, GETDATE())
AND "value" != ' '
"'
DECLARE #logtext varchar(1000)
DECLARE #cmd varchar(2000)
SET #cmd = 'bcp ' + #logtext + ' queryout "C:\Users\anduaguibe\Documents\Visual Studio 2017\Projects\HelloWorld\HelloWorld\upstreamData.txt" -U uID -P uPass -c'
EXEC master...XP_CMDSHELL #cmd
bcp has always worked for me when pushing result sets out to a file, so that's good, as far as I can see.
The bigger problem here is how you're formatting the #logtext query string; You need to escape out the single quote by adding a second one before it. Here are a couple of problem spots for you:
WHERE category = 'L-FAIL-MSG'
and
AND ''value'' != ' '
In the first instance, you're giving it a string and then a literal and then another string, without any formatting.
You need to either add that second quote to escape it and treat L-FAIL-MSG as a string literal, or make L-FAIL-MESSAGE a variable push that into the string.
The second instance will give you an issue, because you've again not escaped the quote- it appears to be a string followed by another string without any operators to concatenate them or anything.
Here's how it might need to be formatted
WHERE category = ''L-FAIL-MSG''
and
AND ''value'' != '' ''

Splitting a string in SQL using MySQL

I need to take a postal code looking like:
S7Y 6H5
that's in a table and display it as
S7Y & 6H5
I can't find a command that splits the string in sql.
MySQL doesn't include a split function, but it does include a replace. You could use:
SELECT REPLACE('S7Y 6HS', ' ', ' & ')
The greater question for me, though, is why don't you do that in your application code?
Try this:
Select REPLACE ('S7Y 6H5', ' ', ' & ')
you can use INSERT INSERT(str,pos,len,newstr)
SELECT INSERT('S7Y 6H5', 4, 0, ' & ');
http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_insert