UPDATE only a part of a string value in a column - sql-server

I am new to t-sql. I have a column which stores values as url's. I want to change the first part of the url's (string), and replace only this part with another url. For example, [url//lsansps01/PMO/ITG0038 iSCOMBI Data Model Project] to [url2//lwazitest.lionsure.com/PMO/ITG0038 iSCOMBI Data Model Project]
This is my update query:
UPDATE dbo.RowUpdates
SET ProjectWorkspaceInternalHRef = REPLACE ProjectWorkspaceInternalHRef, url//lsansps01/, url2//lwazitest.lionsure.com/PMO/ITG0038 iSCOMBI Data Model Project
FROM RowUpdates
WHERE ProjectWorkspaceInternalHRef LIKE url

REPLACE uses () and not comma delimited parameters,
UPDATE dbo.RowUpdates
SET ProjectWorkspaceInternalHRef = REPLACE(ProjectWorkspaceInternalHRef, 'url//lsansps01/', 'url2//lwazitest.lionsure.com/PMO/ITG0038 iSCOMBI Data Model Project')
FROM RowUpdates
WHERE ProjectWorkspaceInternalHRef LIKE url
another questionable part is LIKE url for it to work there should be '%'+url+'%' or something similar.

You want to look at MSDN: REPLACE (Transact-SQL)
from the article:
REPLACE ( string_expression , string_pattern , string_replacement )
so you'd want to change your replace statement to (remember to use a quote (') around your strings):
UPDATE dbo.RowUpdates
SET ProjectWorkspaceInternalHRef =
REPLACE(ProjectWorkspaceInternalHRef, 'url//lsansps01/', 'url2//lwazitest.lionsure.com/PMO/ITG0038 iSCOMBI Data Model Project')
FROM RowUpdates
WHERE ProjectWorkspaceInternalHRef LIKE url
It's also worth looking at the list of String Functions (Transact-SQL) you get in SQL Server.

Replace() function will not give your expected results if #OldUrl text is found in the middle of the ProjectWorkspaceInternalHRef.
If you want to replace only the front bit, use RIGHT() (or SUBSTRING()) function after filtering them out with LEFT() function.
DECLARE #OldUrl VARCHAR(500) = 'YourOdlUrl',
#NewUrl VARCHAR(500) = 'YourNewUrl'
UPDATE dbo.RowUpdates
SET ProjectWorkspaceInternalHRef = #NewUrl +
RIGHT(ProjectWorkspaceInternalHRef, LEN(ProjectWorkspaceInternalHRef) - LEN(#OldUrl ))
WHERE LEFT(ProjectWorkspaceInternalHRef, LEN(#OldUrl )) = #OldUrl

Related

SQL XML parsing using a attribute value supplied by another field in the same row

Context: I'm scraping some XML form descriptions from a Web Services table in hopes of using that name to identify what the user has inputted as response. Since this description changes for each step (row) of the process and each product I want something that can evaluate dynamically.
What I tried: The following was quite useful but it returns a dynamic attribute query result in it's own field ans using a coalesce to reduce the results as one field would lead to it's own complications: Get values from XML tags with dynamically specified data fields
Current Attempt:
I'm using the following code to generate the attribute name that I will use in the next step to query the attribute's value:
case when left([Return], 5) = '<?xml'
then lower(cast([Return] as xml).value('(/response/form/*/#name)[1]','varchar(30)'))
else ''
end as [FormRequest]
And as part of step 2 I have used the STUFF function to try and make the row-level query possible
case when len(FormRequest)>0
then stuff( ',' + 'cast([tmpFormResponse] as xml).value(''(/wrapper/#' + [FormRequest] + ')[1]'',''varchar(max)'')', 1, 1, '')
else ''
end as [FormResponse]
Instead of seeing 1 returned as my FormReponse feild value for the submit attribute (please see in yellow below) it's returning the query text -- cast([tmpFormResponse] as xml).value('(/wrapper/#submit)1','varchar(max)') -- instead (that which should be queried).
How should I action the value method so that I can dynamically strip out the response per row of XML data in tmpFormResponse based on the field value in the FormRequest field?
Thanx
You can check this out:
DECLARE #xml XML=
N'<root>
<SomeAttributes a="a" b="b" c="c"/>
<SomeAttributes a="aa" b="bb" c="cc"/>
</root>';
DECLARE #localName NVARCHAR(100)='b';
SELECT sa.value(N'(./#*[local-name()=sql:variable("#localName")])[1]','nvarchar(max)')
FROM #xml.nodes(N'/root/SomeAttributes') AS A(sa)
Ended up hacking up a solution to the problem by using PATINDEX and CHARINDEX to look for the value in the [FormRequest] field in the he tmpFormResponse field.

Update data inside a view in SQL server

I have some data that looks as follows
As seen, the req_uri column, has data that contains ids after the second slash. I am only interested in the stem of the uri, that is the part before the second uri.
How can I create a view, where the req_uri is updated to only contain values in either '/v1/org' or '/v1/registration'
event_id req_uri
0007845f-cf6c-4513-9a5f-96d02482ef78 /v1/org/6970b2a5-e220-4d68-8fc0-2992a1b8bdb7
000a1fb0-ac4d-489e-866a-7c07caebb959 /v1/registration
000fe2a9-6d76-4045-93ac-9df68971539c /v1/org/6970b2a5-e220-4d68-8fc0-2992a1b8bdb7
0017e50b-c7b5-4e42-b670-f2d9f0af752f /v1/org/e536c1ed-4822-4b88-8c01-9f14c1c583e3/apps
0025a81f-cf81-4c60-8a39-3a626c1092a3 /v1/org/6970b2a5-e220-4d68-8fc0-2992a1b8bdb7
00304cef-87f3-426b-984c-b0b906b4815a /v1/org/e536c1ed-4822-4b88-8c01-9f14c1c583e3/apps
I know how to create views, as follows
CREATE VIEW V_MyView
AS SELECT event_id, req_uri
FROM tableName;
I also know how trim it as follows
update req_uri set req_uri = '/v1/org' where req_uri like '/v1/org%'
However, how can I combine this inside of a view, so that it contains the trimmed data?
Not sure I follow your question 100%, but I think you are asking how to make a view that has an altered hard-coded manipulation of req_uri, so something like this is what you want:
CREATE VIEW V_MyView
AS
SELECT event_id,
CASE WHEN req_uri LIKE '/v1/org%' THEN '/v1/org'
WHEN req_uri LIKE '/v1/registration%' THEN '/v1/registration'
ELSE NULL END as [req_uri]
FROM tableName;

How do you add attributes to an existing Root XML Node using TSQL?

I've constructed some XML in TSQL.
declare #requestXML xml
set #requestXML = (
select #dataXML
for xml raw ('rtEvent')
The general output for what I now have follows the pattern resembling this:
<rtEvent>
<ctx>
.....
</ctx>
</rtEvent>
What I'd like to do now is add some attributes and values to the rtEvent root
element node but I'm not certain how to achieve it.
I've looked at the Modify method of the XML object and have observed the insert, replace value of, and delete operations but cannot seem to figure out how to use any of them to achieve the results I'm after.
Basically, I want to be able to modify the root node to reflect something like:
<rtEvent type="customType" email="someaddress#domain.com"
origin="eCommerce" wishedChannel="0" externalId="5515">
<ctx>
...
</ctx>
</rtEvent>
Should I be using the documented XML.Modify or is there a better method? How should it be done?
Just in case you wanted to see the modify method way of doing it:
DECLARE #requestXML XML = '<rtEvent><ctx>...</ctx></rtEvent>'
SET #requestXML.modify(
'insert
(
attribute type {"customeType"},
attribute email {"someaddress#domain.com"},
attribute origin {"eCommerce"},
attribute wishedChannel {"0"},
attribute externalId {"5515"}
)
into (/rtEvent)[1]')
SELECT #requestXML
it returns this:
<rtEvent type="customeType" email="someaddress#domain.com" origin="eCommerce" wishedChannel="0" externalId="5515">
<ctx>...</ctx>
</rtEvent>
Better use FOR XML PATH, which allows you to specify the naming and aliases as you like them:
SELECT 'SomeContext' AS [ctx]
FOR XML PATH('rtEvent')
This will return this:
<rtEvent>
<ctx>SomeContext</ctx>
</rtEvent>
But with the right attributes you get this:
SELECT 'customType' AS [#type]
,'someaddress#domain.com' AS [#email]
,'eCommerce' AS [#origin]
,0 AS [#wishedChannel]
,5515 AS [#externalId]
,'SomeContext' AS [ctx]
FOR XML PATH('rtEvent')
The result
<rtEvent type="customType" email="someaddress#domain.com" origin="eCommerce" wishedChannel="0" externalId="5515">
<ctx>SomeContext</ctx>
</rtEvent>

Updating XML value within MSSQL

replacing XML tag value within a large XML text value MSSQL.
Within MSSQL I have a column called form which is a text column with an extremely large XML. I need to find a certain tag and change the value of that sub tag within the tag from False to True.
This is what I currently have:
USE trainset;
UPDATE dbo.users
SET formxml = REPLACE(CAST(formxml as nvarchar(max)), '%<ttaycheckbox><name>cbTermsConditions</name><cargo>F</cargo></ttaycheckbox>%', '<ttaycheckbox><name>cbTermsConditions</name><cargo>T</cargo></ttaycheckbox>')
WHERE usersid = '0000GARX'
and formname ='ffOrderRpt'
and formxml LIKE ('%<ttaycheckbox><name>cbTermsConditions</name><cargo>F</cargo></ttaycheckbox>%')
It seems like it is doing the update;
However, after this when I do a select on this particular value the value of is still False rather than True.
What am I missing in there that is not causing it to update properly?
replace() doesn't support wildcards. So your where ... like finds the relevant records, but replace finds NOTHING, because it's looking for a literal %.
You can use XML modify and exist:
UPDATE users
SET formxml.modify('replace value of (/ttaycheckbox/cargo/text())[1] with "T"')
WHERE usersid = '0000GARX'
and formname ='ffOrderRpt'
and formxml.exist('/ttaycheckbox/name[text()[1] eq "cbTermsConditions"]') = 1
and formxml.exist('/ttaycheckbox/cargo[text()[1] eq "F"]') = 1

SQL Server - remove HTML Tag from a varchar

I know there are a few about similar topics on here but I can't find one related to my issue, this is it:
I have a table with an ID Column and a QRCode column. each time an item is added the primary key auto increments. The QRCode will scan in to be like the following:
"http://somewebsite.com/12345/987654321"
i want to be able to remove the "http://somewebsite.com/" from the string, I know how to do this in C# however I am unsure of how to do this in Sql Server. any guidance would be great, thanks
Regular formats are like the following, and used in the example below.
"http://somewebsite.com/12345/456564654"
"http://somewebsite.com/12345/989886765"
"http://somewebsite.com/12346/987654321"
the query returns the following results:
SELECT
REPLACE
(
REPLACE(QRCode, 'http://somewebsite.com/', '')
,'/', ' '
) AS QRCode
FROM
QRTable
WHERE
QRCode LIKE '%http://somewebsite.com/%'
"12345 456564654"
"12345 989886765"
"12346 987654321"
Now i need to update the table with those new results however as there's 3 results, i get the error message "Subquery returned more than 1 value". is there a way to replace the selected values in the table with the ones that exist based on the primary key field?
**Removed previous example
A more complete answer based on your updated question. This removes the first portion of the URL as well as the trailing / so that you get your desired output.
DECLARE #Variable VARCHAR(50)
SET #Variable = 'http://somewebsite.com/12345/456564654'
SET #Variable =
REPLACE
(
REPLACE(#Variable, 'http://somewebsite.com/', '')
,'/', ' '
)
PRINT #Variable
Output = 12345 456564654
Looking at your SQL statement you want this:
SELECT
REPLACE
(
REPLACE(QRCode, 'http://somewebsite.com/', '')
,'/', ' '
) AS QRCode
FROM
QRTable
WHERE
QRCode LIKE '%http://somewebsite.com/%'

Resources