Output a database and its string - sql-server

I get an error where it states invalid column 'DatabaseSQL' when I try to add a database reference into an OUTPUT statement like below:
OUTPUT [DatabaseSQL] +'.dbo.Package' 'TableName', 'PackageID', inserted.PackageId,
Core.updXMLFragment('StatusID', inserted.StatusID, Deleted.StatusID)
INTO #OutputList
If I remove the DatabaseSQL and added it as a string like OUTPUT 'Database.dbo.Package..., then it works fine, but I need the statement to actually recognise the database as well as add it as a string, just outputting it as a string alone isn't good enough. Any ideas?

You could use: DB_NAME():
OUTPUT DB_NAME() + '.dbo.Package', 'TableName', 'PackageID' ...
If you store DB name in variable use:
DECLARE #DatabaseSQL SYSNAME = QUOTENAME('name with space');
OUTPUT #DatabaseSQL + '.dbo.Package', 'TableName', 'PackageID' ...
LiveDemo

Related

SQL replace value of with always random xml code

I have the following SQL XML in several rows of a table (table is tbldatafeed column in configuration_xml). All of the UserName="" and Password="" is different each time for each row and does not repeat so I can not find/replace off of that. I am trying to write a query that finds all of those and replaces them with Username/Passwords I choose.
<DataFeed xmlns="http://www.tech.com/datafeed/dfx/2010/04" xmlns:plugin="pluginExtensions" Type="TODO" Guid="TODO" UserAccount="DF_LEAN_PopulateCommentsSubForm" Locale="en-US" DateFormat="" ThousandSeparator="" NegativeSymbol="" DecimalSymbol="" SendingNotifications="false" SendJobStatusNotifications="false" RecipientUserIds="" RecipientGroupIds="" RecipientEmailAddresses="" Name="CI_C11.01_Lean-Lean_Reject Comments_A2A" >
<Transporter>
<transporters:ArcherWebServiceTransportActivity xmlns:transporters="clr-namespace:ArcherTech.DataFeed.Activities.Transporters;assembly=ArcherTech.DataFeed" xmlns:out="clr-namespace:ArcherTech.DataFeed;assembly=ArcherTech.DataFeed" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:compModel="clr-namespace:ArcherTech.DataFeed.ComponentModel;assembly=ArcherTech.DataFeed" xmlns:channel="clr-namespace:ArcherTech.DataFeed.Engine.Channel;assembly=ArcherTech.DataFeed" xmlns:engine="clr-namespace:ArcherTech.DataFeed.Engine;assembly=ArcherTech.DataFeed" xmlns:kernel="clr-namespace:ArcherTech.Kernel.Channel;assembly=ArcherTech.Kernel" xmlns="clr-namespace:ArcherTech.DataFeed;assembly=ArcherTech.DataFeed" xmlns:schema="clr-namespace:System.Xml.Schema;assembly=System.Xml" xmlns:xmlLinq="clr-namespace:System.Xml.Linq;assembly=System.Xml" xmlns:domain="clr-namespace:ArcherTech.Common.Domain;assembly=ArcherTech.Common" xmlns:s="clr-namespace:System;assembly=mscorlib" x:Key="transportActivity" SearchType="ReportId" Uri="https://arcs-d" RecordsPerFile="100" ReportID="EC514865-88D5-49CE-A200-7769EC1C2A88" UseWindowsAuth="false" IsWindowsAuthSpecific="false" WindowsAuthUserName="i9XzCczAQ7J2rHwkg6wG9QF8+O9NCYJZP6y5Kzw4be0+cdvUaGu/9+rHuLstU736pnQrRcwmnSIhd6oPKIvnLA==" WindowsAuthPassword="+y0tCAKysxEMSGv1unpHxfg6WjH5XWylgP45P5MLRdQ6+zAdOLSVy7s3KJa3+9j2i83qn8I8K7+1+QBlCJT1E7sLQHWRFOCEdJgXaIr1gWfUEO+7kjuJnZcIEKZJa2wHyqc2Z08J2SKfdCLh7HoLtg==" WindowsAuthDomain="" ProxyName="" ProxyPort="8080" ProxyUsername="" ProxyPassword="" ProxyDomain="" IsProxyActive="False" ProxyOption="None" InstanceName="ARCS-D" TempFileOnSuccessAction="DoNothing" TempFileOnSuccessRenameString="" TempFileOnErrorAction="DoNothing" TempFileOnErrorRenameString="" Transform="{engine:DataFeedBinding Path=Transform}" SessionContext="{engine:DataFeedBinding Path=Session}">
<transporters:ArcherWebServiceTransportActivity.Credentials>
<NetworkCredentialWrapper UserName="TeSZmI1SqO0eJ0G2nDVU+glFg/9eZfeMppYQnPfbeg8=" Password="Slt4VHqjkYscWyCwZK40QJ7KOQroG9OTKr+RGt9bQjE=" />
</transporters:ArcherWebServiceTransportActivity.Credentials>
</transporters:ArcherWebServiceTransportActivity>
</Transporter>
</DataFeed>
I need to be able to set a value and replace it with a query
I have written the following
select #config_xml=configuration_xml from bldatafeed where datafeed_name = 'REMOVED'
update tbldatafeed set configuration_xml.modify(//*:NetworkCredentialWrapper/#UserName)[1] with "abc" ')
where datafeed_name = 'REMOVED'
This does the trick but it only works if I set the "abc" password each time in each area and in some cases I am running this against 50+ rows.
I also tried:
Declare #server nvarchar(max) = 'abc'
Declare #config_xml xml
select #config_xml=configuration_xml from bldatafeed where datafeed_name = 'REMOVED'
update tbldatafeed set configuration_xml.modify(//*:NetworkCredentialWrapper/#UserName)[1] with #server ')
where datafeed_name = 'REMOVED'
The error from this is that: XQuery [tbldatafeed.configuration_xml.modify()]: Top-level attribute nodes are not supported
What I would like to be able to do is set my variable and utilize that as I will be setting this up for multiple rows and unfortunately this error is making this a very difficult problem to solve.
Thanks for any help, this has kept me confused for a bit.
Use the function sql:variable() to use a variable in the XQuery expression.
declare #T table(X xml);
insert into #T values('<X UserName=""/>');
declare #UserName nvarchar(max) = 'abc'
update #T set
X.modify('replace value of (/X/#UserName)[1]
with sql:variable("#UserName")');

Update with wildcard

in need to update all the rows that have sub string like this:
'forcestartpage=xx'and replace it with 'forcestartpage=18'
* there is lots of characters before and after the substring that shouldnt change
tried this, doesnt work:
update t_reminderscont
set body = REPLACE (body,'forcestartpage=__','forcestartpage=18')
thanks
You can get away with a STUFF function:
SELECT
T.body,
Replaced = STUFF(
T.Body, -- Insert in T.Body
CHARINDEX('forcestartpage=', T.Body), -- ... at the position where 'forcestartpage=' starts
LEN('forcestartpage=18'), -- ... while replacing 17 characters
'forcestartpage=18') -- ... the value forcestartpage=18
FROM
YourTable AS T
WHERE
T.body LIKE '%forcestartpage=__%' AND
T.body NOT LIKE '%forcestartpage=18%'
However this will only work for the first appearance of the forcestartpage= on each row.

Remove characters from text using TRANSLATE function (replace them with empty strings)

Let's say I have a string:
DECLARE #text VARCHAR(20) = 'abr_akad-ab#ra';
and I want to remove all _-# characters from the text.
Normally I would user REPLACE function to that, something like:
SELECT REPLACE(REPLACE(REPLACE(#text, '-', ''), '_', ''),'#','')
Can I do that with single TRANSLATE statement somehow?
You can try the following query:
DECLARE #text AS VARCHAR(20) = 'abr_akad-ab#ra';
SELECT REPLACE(TRANSLATE(#text, '_-#', '###'), '#', '')
it will return the output as abrakadabra
Working demo on db<>fiddle
You'll still need use REPLACE at some point, as SQL Server requires that the length of parameters 2 and 3 for TRANSLATE are the same length. As such an expression like the below will error:
TRANSLATE(YourColumn, '-_#','')
Therefore what you could do it replace them all with a different character using TRANSLATE, and then replace that one character:
REPLACE(TRANSLATE(YourColumn, '-_#','|||'),'|','')

Sql Server wildcard Like Statement : How to use for data having undefined Length

I have URL data in a table like this(Showing only one row i have many more in table)
abc/portfolio/12/strategy
abc/portfolio/15/strategy
abc/portfolio/1/strategy
The data is in four part separated with '/'.
i got a string to match with this data, either i got a same string to match or if i can get "*" at any part of data if i don't need to match the particular part Like
abc/portfolio/*/strategy
if i get this string to match i don't have to match the '*' part,rest i need to match with the data. i need to match abc/portfolio/% with i need to Match %/strategy in a single column data.
i don't know how to do it with wildcards also as in data its not define that what is the length of a particular part.
As well as if i got two '**' then i need to match only intial Part of Data
Like if i get data to match abc/**/12/strategythen i only need to match abc\% in data.
Example:
Select Url_data from schema1.table1
where
url_data Like 'abc/portfolio/*/strategy'
here i need the "*" to work like, ignore the data in that particular Part.
outcome expected is :
abc/portfolio/12/strategy
abc/portfolio/15/strategy
abc/portfolio/1/strategy
Instead of "*" you can use '%' as follows
Select Url_data from schema1.table1
where
url_data Like 'abc/portfolio/%/strategy'
declare #v varchar(100) = 'abc/portfolio/*/strategy'
Select Url_data from schema1.table1 where url_data Like
replace(
case
when charindex('**',#v) > 0 then left(#v, charindex('**',#v))
else #v
end
,'*','%')
This will replace the * by % if only one * is in the variable #v or truncate the text after ** and replace ** it by %.
declare #v varchar(100) = 'abc/portfolio/*/strategy' -> abc/portfolio/%/strategy
declare #v varchar(100) = 'abc/portfolio/**/strategy' --> abc/portfolio/%

Using SQL WHERE LIKE to filter when have consecutive numbers

Trying to convert a PostgreSQL view to SQL Server (2016) view.
I have a table with a column named filename, with the following data:
R24bMP1.png
MP3.png
R28.jpg
I002.jpg
App_1472669569054.jpg
Test_1575753047890.png
So, I like to filter all rows the filename must contains 13 consecutives numbers, in the example, only App_1472669569054.jpg and Test_1575753047890.png.
In PostgreSQL, I can use regex to do this:
SELECT * FROM table WHERE filename ~ '\d{13}'.
Tried in SQL Server with:
SELECT * FROM table WHERE filename LIKE '%[0-9]{13}%', but got no results. The only way that worked is:
SELECT * FROM table WHERE filename LIKE '%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%'
After that, I need to get only the number part of filename, in the example, the returned value must be:
1472669569054
1575753047890
I know I can use CLR with SQL Server, but I like to known if is possible to filter without CLR in this case.
As Martin Smith pointed out:
'%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%'
can be reduced to:
'%' + replicate('[0-9]',13) + '%'
You were most of the way there:
declare #filename varchar(128) = 'Test_1575753047890.png'
select test=substring(#filename
,patindex('%' + replicate('[0-9]',13) + '%',#filename)
,13
)
returns: 1575753047890
So for your table it would look like:
select test=substring([filename]
,patindex('%' + replicate('[0-9]',13) + '%',[filename])
,13
)
from t
where patindex('%' + replicate('[0-9]',13) + '%',[filename]) > 0

Resources