find exact string match and replace it in sql server - sql-server

Is there a (supposedly) simple way to get an exact match when using the replace function in SQL Server 2012? (I'm open to other searching possibilities as well, of course)
For example, I'm using the following code to grab all the objects in a DB containing 'texter' in it at some point:
select OBJECT_NAME(object_id) name,
OBJECT_DEFINITION(object_id) code,
type
into #tester
from sys.objects
where OBJECT_DEFINITION(object_id) LIKE '%texter%'
This doesn't seem to differentiate between .texter, #texter or stupidtexter.
and so if I use:
update #tester
set code = REPLACE(code, 'texter', 'bluenose')
where code LIKE '%texter%'
It's going to replace any variant of 'texter' with 'bluenose'
Let's assume I only want to replace the ' texter' and '.texter' versions of this and nothing else (noting that within each object it is possible that #texter or stupidtexter may also be present in the object code).
Is there a way I can differentiate between the variants of 'texter', #texter and stupidtexter?
Thanks

The solution was:
replace(REPLACE(code, '.texter', 'bluenose'), ' texter', 'bluenose')
Thanks to Sean Lange for the answer!

Related

Why Hibernate HSQL Concat is not working for MSSQL?

So, I have Hibernate 5.3.1 in a project which connects to different enginees (MySql, Oracle, PostgreSQL and MS SQL), so I can't use native queries.
Let's say I have 3 records in a table, which all of them have the same datetime, but I need to group them only by date (not time). For example, 2019-12-04;
I execute this query:
SELECT
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)),
iss.code,
COUNT(tx.id)
FROM
tx_ tx
JOIN
issuer_ iss
ON
tx.id_issuer = iss.id
GROUP BY
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)), iss.code
But, when I test it connected to SQL SERVER 2017, instead of return 20191204, it's returning 2035. In Oracle and MySQL is working fine.
Anyone has any idea why is this happen? I've tried different ways, like use + instead of CONCAT but the result is the same.
I've also tried to extract them for separate (without concat), and they have been returning correct. The problem is, I need to group them by the complete date.
And just for the record, the field is declared as datetime2 in DDBB
How about simply adding them, instead of using CONCAT.
(year(tx.date_)*10000 + month(tx.date_)*100 + day(tx.date_)*1) AS datenum
Thus, try this:
SELECT
CAST((year(tx.date_)*10000 + month(tx.date_)*100 + day(tx.date_)*1) AS string) AS datenum,
iss.code
FROM tx_ tx
JOIN issuer_ iss
ON tx.id_issuer = iss.id
GROUP BY year(tx.date_), month(tx.date_), day(tx.date_), iss.code
Thanks for the hint Gert Arnold gave me. I just didn't realize that the query was adding like if they were numbers in MSSQL.
Finally, I manage to make it work in the 4 RDBMS casting to string first
SELECT
CONCAT(CAST(year(tx.date_) AS string), CAST(month(tx.date_) AS string), CAST(day(tx.date_) AS string)),
iss.code
FROM
tx_ tx
JOIN
issuer_ iss
ON
tx.id_issuer = iss.id
GROUP BY
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)), iss.code
I tried also casting to TEXT, but it throws exception in MySQL
Why use concat() to begin with?
Assuming Hibernate takes care of converting the non-standard year(), month() and day() functions, then the following should work on any DBMS
SELECT year(tx.date_), month(tx.date_), day(tx.date_), iss.code
FROM tx_ tx
JOIN issuer_ iss ON tx.id_issuer = iss.id
GROUP BY year(tx.date_), month(tx.date_), day(tx.date_), iss.code

SQL: Using XML as input to do an inner join

I have XML coming in as the input, but I'm unclear on how I need to setup the data and statement to get the values from it. My XML is as follows:
<Keys>
<key>246</key>
<key>247</key>
<key>248</key>
</Keys>
And I want to do the following (is simplified to get my point across)
Select *
From Transaction as t
Inner Join #InputXml.nodes('Keys') as K(X)
on K.X.value('#Key', 'INT') = t.financial_transaction_grp_key
Can anyone provide how I would do that? What would my 3rd/4th line in the SQL look like?
Thanks!
From your code I assume this is SQL-Server but you added the tag [mysql]...
For your next question please keep in mind, that it is very important to know your tools (vendor and version).
Assuming T-SQL and [sql-server] (according to the provided sample code) you were close:
DECLARE #InputXml XML=
N'<Keys>
<key>246</key>
<key>247</key>
<key>248</key>
</Keys>';
DECLARE #YourTransactionTable TABLE(ID INT IDENTITY,financial_transaction_grp_key INT);
INSERT INTO #YourTransactionTable VALUES (200),(246),(247),(300);
Select t.*
From #YourTransactionTable as t
Inner Join #InputXml.nodes('/Keys/key') as K(X)
on K.X.value('text()[1]', 'INT') = t.financial_transaction_grp_key;
What was wrong:
.nodes() must go down to the repeating element, which is <key>
In .value() you are using the path #Key, which is wrong on two sides: 1) <key> is an element and not an attribute and 2) XML is strictly case-sensitive, so Key!=key.
An alternative might be this:
WHERE #InputXml.exist('/Keys/key[. cast as xs:int? = sql:column("financial_transaction_grp_key")]')=1;
Which one is faster depends on the count of rows in your source table as well as the count of keys in your XML. Just try it out.
You probably need to parse the XML to a readable format with regex.
I wrote a similar event to parse the active DB from an xmlpayload that was saved on a table. This may or may not work for you, but you should be able to at least get started.
SELECT SUBSTRING(column FROM IF(locate('<key>',column)=0,0,0+LOCATE('<key>',column))) as KEY FROM table LIMIT 1\G

SQL Server - add to this query to first check for existence of a string

I have an nvarchar field in my database called CatCustom which contains comma-separated 5-character codes. It can contain as little as one code, or as many as 20 codes, separated by commas.
Right now, I use this query to add a new 5-character code to the field in given records (in this case the new code is LRR01):
UPDATE dbo.Sources
SET CatCustom = CONCAT_WS(', ', RTRIM(CatCustom), 'LRR01')
WHERE SourceID IN (1,2,3,4,5,8,9,44,63,45,101,102,222,344)
I need to add to this though: I need the record to be updated only if that 5-character code doesn't already exist somewhere in the CatCustom field, to ensure that code is not in there more than once.
How would I accomplish this?
EDIT: I really don't understand how this can be considered a duplicate of the suggested thread. This is a VERY specific case and has nothing to do with creating stored procedures and or variables. The alleged duplicated thread does not really help me - sorry.
Use STRING_SPLIT function to split the comma separated list and then add Not Exist condition in the WHERE clause like below
UPDATE dbo.Sources
SET CatCustom = CONCAT_WS(', ', RTRIM(CatCustom), 'LRR01')
WHERE SourceID IN (1,2,3,4,5,8,9,44,63,45,101,102,222,344)
AND NOT EXISTS (SELECT 1 FROM STRING_SPLIT(CatCustom, ',') where value = 'LRR01')
UPDATE dbo.Sources
SET
CatCustom = CONCAT_WS(', ', RTRIM(CatCustom), 'LRR01')
WHERE
SourceID IN (1,2,3,4,5,8,9,44,63,45,101,102,222,344)
AND CatCustom NOT LIKE '%LRR01%';

Access SQL Like * alternative in MS SQL server

I'm working on a project that has a search engine. AS we know in MS ACCESS we could use "*" in Queries under Criteria field to retrieve all records.
In SQL Server I need the same technique. I have tried different LIKE with WHERE Clauses. But I still didn't get the exact result I want.
In this project I have 3 textboxes (Category, Item, Location). If the user leaves any of them empty. I want to retrieve all the records.
I need something like this:
string t1,t2,t3;
if(!String.IsNullOrEmpty(txtCategory.Text))
t1=txtCategory.Text;
else
t1="*";
if(!String.IsNullOrEmpty(txtItem.Text))
t2=txtItem.Text;
else
t2="*"
if(!String.IsNullOrEmpty(txtLoc.Text))
t2=txtLoc.Text;
else
t3="*";
-
-
-
// in a function i have this :
SELECT * FROM Table_Items WHERE Category='"+t1+"' AND Item='"+t2+"' AND Location='"+t3+"'"
in ms sql server you can use the same technique but instead of * you should use %.
for examples:
%: means any
a%: all strings that start with a
%z: all strings that end with z
SO, your code should look like something as below:
// codes here
t3="%";
WHERE ColumnName LIKE t3
or
Where ColumnName LIKE '%'
I hope that will help you.
Change your * to the %
... Where Category Like "'+t1+"' and Item Like '"+t2+"' ...

DB2 -- How to use LTRIM scalar function with 2 arguments?

I am new to DB2 (using version 10.1) and I'm trying to execute a simple ltrim function in a test query.
select ltrim(',1,2,3,4', ',') from sysibm.sysdummy1;
This results in the following error:
DB2 SQL Error: SQLCODE=-440, SQLSTATE=42884, SQLERRMC=LTRIM;FUNCTION, DRIVER=3.65.77
Based on the documentation here, it seems my example should work. Note, I can use the alternative trim function or the 1-arg version of ltrim:
select trim(l ',' from ',1,2,3,4') from sysibm.sysdummy1;
select ltrim(' test') from sysibm.sysdummy1;
And those works fine!
Are there some fundamental differences between the 2-arg form of ltrim and the other examples I provided?
This function was added in DB2 10.1 fix pack 2 -- you may want to upgrade.
Making some guesses here, but are you sure you're on 10.1? That version of that function you're trying to use appears to have been added in 10, so if you're on 9.x, it won't work.
If you are, you might check and see if your schema path includes SYSIBM:
SELECT CURRENT_PATH FROM SYSIBM.SYSDUMMY1
The "old" one-argument version of the function is in SYSFUN, which (if your path doesn't include SYSIBM) might be why you're still able to use that version.
If SYSIBM isn't in your path, you can try changing it using:
SET PATH = SYSIBM, CURRENT_PATH
Why not try STRIP() instead:
VALUES STRIP(',1,2,3,4', L, ',');
(side note: It is simpler to use the VALUES statement, rather than SELECT FROM SYSIBM.SYSDUMMY1)

Resources