SQL Server : display data/column from SELECT statement - sql-server

I have a table with data that holds a bunch of HTML attributes.
For example: '<HTML><BODY></BODY></HTML>'
I would like to be able to write a SELECT statement that can grab those values, but display them modified.
So instead of displaying
'<HTML><BODY>DATA</BODY></HTML>'
I want to show:
'<HTML>
<BODY>DATA</BODY>
</HTML>'
Essentially, breaking out each one to a new line, based on finding a '>' value, without modifying the data.
I can't seem to find a way to do this. I tried looking into STRING_SPLIT, but I can't get that to apply from the SELECT part.
Any suggestions where I look?
Edit 2/22 - it appears REPLACE gets me further, but when reviewing this more, it may not be possible.
How would SQL know to break out to a new line when the ending HTML tag appears?
It's almost like I need to use a RegEx in here...
REPLACE(TD.DefDetails, '</', CHAR(13) + CHAR(10) + '</') As DefDetails

STRING_SPLIT can split a single column into multiple rows. STRING_SPLIT does require SQL Server Version 2016+. The following snippet does show an example for this scenario.
USE tempdb;
GO
DECLARE #HTMLString AS VARCHAR(100) = '<HTML><BODY></BODY></HTML>';
SELECT *
FROM STRING_SPLIT(#HTMLString,'>');

Actually appears this is done using REPLACE.
REPLACE(Table.DefDetails, '>', '>'+ CHAR(13) + CHAR(10)) As DefDetails

Demo on db<>fiddle
You can achieve it in this way
SELECT REPLACE('<HTML><BODY></BODY></HTML>', '>', '>'+ CHAR(13))
Or if you want to get the value into rows, you can do this way.
Select value + '>'
from STRING_SPLIT('<HTML><BODY></BODY></HTML>', '>')
where value <> ''
Output

Related

Using TSQL and XQuery to extract values from XML

I have a table with an XML column. Some of the XML is very large (8MB) but I'll present a simpler version of the problem here. Overall, I need to update the table and find those rows where the XML contains a node named <CompressedPart> at a known point in the XML tree, take its value, base64-decode it and replace <CompressedPart> with the resulting data.
This question is simply just the first part of that, which is trying to extract the text under a point in the XML tree. I've encountered XQuery once before and it just as life-destroying as it appears to be now.
To this end, I've simplified the XML to just two nodes thus:
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
</GovTalkMessage>
and I'm simply trying to get the value "2.0". The code I'm using is:
SELECT CAST('<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
</GovTalkMessage>' AS XML).value('(/GovTalkMessage/EnvelopeVersion)[1]', 'VARCHAR(MAX)')
but this returns NULL. I've tried removing/adding forward slashes, removing the [1] (which gives the incredible un-useful error message "requires a singleton"). Whatever I specify in the XQuery I just get NULL or an error.
In time I will want to select across the whole table, as below, so I'm not just looking for a solution that works for a single XML variable in the FROM clause as I've seen in other examples. This type of thing:
SELECT GOVTALK_XML_INPUT_DATA.value('(/GovTalkMessage/EnvelopeVersion)[1]', 'VARCHAR(MAX)')
FROM dbo.IndividualSubmission
How do I go about querying to solve just this first part of my issue?
A couple ways..
DECLARE #X XML = '
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
</GovTalkMessage>';
SELECT #X.value('(//*:EnvelopeVersion/text())[1]', 'varchar(20)');
Or..
DECLARE #X VARCHAR(1000) = '
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
</GovTalkMessage>';
SELECT CAST(#X AS XML).value('(//*:EnvelopeVersion/text())[1]', 'varchar(20)');

Converting Oracle statement to SQL Server format

Below is an Oracle script that I need to execute on an SQL Server.
SELECT
records.pr_id,
SUBSTR (REPLACE (REPLACE (XMLAGG (XMLELEMENT ("x", prad4.selection_value)
ORDER BY prad4.selection_value),'</x>'),'<x>',' ; '),4) as teva_role
FROM records
Thanks for the help,
Barry
I programmed in SQL for years in several environments and it is about 75% the same. So, the SQL statement should work as is, however the functions (REPLACE, SUBSTR) will be what you need to research and change.
Also, you get columns from prad4 without including it in the FROM statement which is a problem.
And, finally, your parentheses aren't balanced which, I would think, would be a problem in Oracle as well.
This is basically concatenating a set of strings with a delimiter. The common way to do this, is using FOR XML PATH('') which seems to be the equivalent of the combination of XMLELEMENT() in Oracle, but with a different syntax. You can also use XML functions to prevent change of certain characters not allowed in XML. The STUFF takes care of the SUBSTR() part of your code. For a more detailed explanation, you can read this article on Creating a comma-separated list.
The code should look similar to this:
SELECT records.pr_id,
STUFF(( SELECT ' ; ' + prad4.selection_value
FROM prad4
WHERE prad4.pr_id = records.pr_id
ORDER BY prad4.selection_value
FOR XML PATH(''), TYPE).value('./text()[1]', 'varchar(max)'), 1, 3, '')
FROM records;
Of course, with the improvements of SQL Server 2017, the code can be simplified to something like this:
SELECT records.pr_id,
STRING_AGG( selection_value, ' ; ') WITHIN GROUP (ORDER BY selection_value ASC)
FROM records;

Join query with user provided data-T-sql

I have a requriment where user will provide many Ids(in Hundres/thousands) in a Text area in vb.net app, I need to use these IDs in T-Sql(Sql Server) to get the data. I dont want to save these Ids in any database table. Just want to pass using a paramater (type of varchar(max)) and use in the procedure.
actually, only read access is permitted for the vb application users.It is Sql-2005 database.Id field is atleaset 12 to 15 characters length.The user will copy/paste data from other source may be CSV or Excel file.
any idea how can i achive this.
any help is appreciated.
Thanks
If you do not want to use Table Valued Parameters, as suggested elsewhere, and you don't want to store the ID's in a temporary table, you can do the following.
Assuming your ID's are integer values, that are separated by commas, in the parameter string, you can use the LIKE operator in your SQL-statement's WHERE filter:
Say you have a parameter, #IDs of type varchar(max). You want to get only those records from MyTable where the ID-column contains a value that has been typed into the #IDs-parameter. Then your query should look something like this:
SELECT * FROM MyTable
WHERE ',' + #IDs + ',' LIKE '%,' + CAST(ID AS varchar) + ',%'
Notice how I prepend and append an extra comma to the #IDs parameter. This is to ensure that the LIKE operator will still work as expected for the first and last ID in the string. Make sure to take the nescessary precautions against SQL injection, for example by validating that users are only allowed to input integer digits and commas.
Try using CHARINDEX:
DECLARE #selectedIDs varchar(max) = '1,2,3'
Set #selectedIDs = ',' + #selectedIds + ',' --string should always start and end with ','
SELECT * FROM YourTable
WHERE CHARINDEX(',' + CAST(IDColumn as VARCHAR(10)) + ',', #selectedIds) > 0

line breaks lost in sql server

I am entering error information into an ErrorLog table in my database. I have a utility class to do this:
ErrorHandler.Error("Something has broken!!\n\nDescription");
This works fine. However, when I try to access this table, the line breaks no longer seem to be present.
If I SELECT the table:
SELECT * from ErrorLog ORDER BY ErrorDate
there are no line breaks present in the log. This is kind of expected, as line breaks in one-line rows would break the formatting. However, If I copy the data out, the line break characters have been lost, and the data is all on one line.
How do I get line breaks in data at the end of my query when I put line breaks in? I don't know if the string has been stripped of line breaks when it enters the table, or if the viewer in SQL Server Management Studio has stripped out the line breaks.
The data type of the column into which error messages are put is nvarchar(Max), if that makes a difference.
EDIT: Unexpectedly, Pendri's solution didn't work.
Here is an excerpt of the string just before it passes into the SQL server:
POST /ipn/paymentResponse.ashx?installation=272&msgType=result HTTP/1.0\n\rContent-Length: 833\n\rContent-Type:
And here is the same string when I extract it from the grid viewer in SQL Server Management Studio:
POST /ipn/paymentResponse.ashx?installation=272&msgType=result HTTP/1.0 Content-Length: 833 Content-Type:
The place where the line break should be has been double spaced.
Any ideas?
No need to replace string input\output, you need just pick up correct option:
Tools -> Options...
> Query Results
> SQL Server
> Results to Grid
set "Retain CR\LF on copy or save" to true.
And don't forget to restart your management studio!
according Charles Gagnon answer
SSMS replaces linebreaks with spaces in the grid output. If you use Print to print the values (will go to your messages tab) then the carriage returns will be displayed there if they were stored with the data.
Example:
SELECT 'ABC' + CHAR(13) + CHAR(10) + 'DEF'
PRINT 'ABC' + CHAR(13) + CHAR(10) + 'DEF'
The first will display in a single cell in the grid without breaks, the second will print with a break to the messages pane.
A quick and easy way to print the values would be to select into a variable:
DECLARE #x varchar(100);
SELECT #x = 'ABC' + CHAR(13) + CHAR(10) + 'DEF';
PRINT #x;
Update a couple years later.
As described here, one solution to preserve viewing linebreaks in SSMS is to convert the output to XML:
SELECT * FROM (
SELECT * from ErrorLog ORDER BY ErrorDate
) AS [T(x)] FOR XML PATH
Fortunately, if you have SSMS 2012, this is no longer an issue, as line breaks are retained.
I echo David C's answer, except you should use the "TYPE" keyword so that you can click to open the data in a new window.
Note that any unsafe XML characters will not work well with either of our solutions.
Here is a proof of concept:
DECLARE #ErrorLog TABLE (ErrorText varchar(500), ErrorDate datetime);
INSERT INTO #ErrorLog (ErrorText, ErrorDate) VALUES
('This is a long string with a' + CHAR(13) + CHAR(10) + 'line break.', getdate()-1),
('Another long string with' + CHAR(13) + CHAR(10) + '<another!> line break.', getdate()-2);
SELECT
(
SELECT ErrorText AS '*'
FOR XML PATH(''), TYPE
) AS 'ErrorText',
ErrorDate
FROM #ErrorLog
ORDER BY ErrorDate;
I can confirm that the line breaks are preserved when copying out of a grid in SSMS 2012.
try using char(13) + char(10) instead of '\n' in your string (define a constant and concatenate to your sql)
Another simple solution is to click the "results to text" button in SSMS. Its not super clean, but gives you visibility to line breaks with about half a second of work.
For SQL Server 2008, there is no provision to set "Retain CR\LF on copy or save" to true.
For this issue, what I did is that, replace char(13) with "\r" and replace char(10) with "\n" like below.
REPLACE(REPlACE([COLUMN_NAME],char(13), '\r'),CHAR(10),'\n')
And in the code-behind again I've replaced "\r\n" with a break tag.
I worked out in this way as there was no option provided in SQL 2008 as mentioned above. This answer might be an alternative though.
Thanks

sql server full text search, replace, near and forms of

Im getting trouble with a full text search query. First, my first try is not working because theres a syntax error close to replace (and I dont understand why) (if I do the replace outside the contains it works):
declare #what varchar(100) = 'word1 word2'
select *
from tablea
where
contains(column1, replace(#what, ' ', ' near '))
My second problem is about the NEAR and FORMS OF syntax. I tried:
'formsof(inflectional, "word1") near formsof(inflectional, "word2")'
But its not working. Theres a syntax error too, not in the replace thing, but in the query. Is it possible to use a replace over the #what variable (outside or inside the contains) to get the correct syntax?

Resources