Splitting a string in SQL using MySQL - 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

Related

Save the xml result to a column in a SQL table

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!!!

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;

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'' != '' ''

how to print data of SUBSTRING_INDEX( ) field in mysql

$qry=mysql_query(SELECT title,SUBSTRING_INDEX( blog, ' ', 15),user_id,date_time
FROM blog_tab WHERE status='Active');
while($res=mysql_fetch_array($qry))
{
echo $res['blog'];
}
i use above query to show some content of paragraph in ma page but it do not allow to write the field which uses the function SUBSTRING_INDEX().how i can print the field of table with SUBSTRING_INDEX().
Well, the column name in this case is not blog, it is SUBSTRING_INDEX( blog, ' ', 15), so you would access it with $res["SUBSTRING_INDEX( blog, ' ', 15)"], or since you are using mysql_fetch_array you can access it with $res[1]. However, I suggest you alias it, for easier acces, and use mysql_fetch_assoc, like:
$qry=mysql_query("SELECT title,SUBSTRING_INDEX( blog, ' ', 15) AS blog,user_id,date_time
FROM blog_tab WHERE status='Active'");
while($res=mysql_fetch_assoc($qry))
{
echo $res['blog'];
}
NOTE: You should not use mysql_* functions as they are deprecated and will no longer be supported. Read more at http://au1.php.net/mysql_query

MySQL to JSON not formed properly

I am trying to return JSON formatted results from a MySQL query but cannot get the correct format - it needs to be e.g.
{comCom:'test 3', comUid:'63',... etc
But what I'm getting is without apostrophes
{comCom:test 3, comUid:63,... etc
I am running the query in PHP as follows (shortened for ease of reading)
$result = mysql_query("select...
...GROUP_CONCAT(CONCAT('{comCom:',ww.comment, ', comUid:',h.user_id,', comName:',h.name,', comPic:',h.live_prof_pic,',comUrl:',h.url,',comWhen:',time_ago(ww.dateadded),'}')) comment,...
How can I get the punctuation?
I know mysql_query is deprecated btw, just in process of moving things to MySQLi
Can you not just escape the ' character with \'?
...GROUP_CONCAT(CONCAT('{comCom:\'',ww.comment, '\', comUid:\'',h.user_id,'\', comName:\'',h.name,'\', comPic:\'',h.live_prof_pic,'\',comUrl:\'',h.url,'\',comWhen:\'',time_ago(ww.dateadded),'\'}'))
or use a mixture of " with '
...GROUP_CONCAT(CONCAT("{comCom:'",ww.comment, "', comUid:'",h.user_id,"', comName:'",h.name,"', comPic:'",h.live_prof_pic,"',comUrl:'",h.url,"',comWhen:'",time_ago(ww.dateadded),"'}"))