Replace ; with blank in SQL - sql

I have a table like this:
DECLARE #T TABLE
(note VARCHAR (50))
INSERT #T
SELECT 'Amplifier'
UNION ALL SELECT ';'
UNION ALL SELECT 'Regulator'
How can I replace the semicolon (';') with blank ('').
Expected Output:
Amplifier
'' -- here semicolon replace with blank
Regulator

If you want to replace ALL semicolons from any outputted cell you can use REPLACE like this:
SELECT REPLACE(note,';','') AS [note] FROM #T

Fetching from the given table, use a CASE statement:
SELECT CASE WHEN note = ';' THEN '' ELSE note END AS note FROM #T;
replace() would replace all occurrences of the character. Doesn't seem like you'd want that. This expression only replaces exact matches of the whole string.

It looks like you need to REPLACE all your semicolons:
DECLARE #T TABLE
(note VARCHAR (50))
INSERT INTO #T
SELECT REPLACE(SourceColumn, ';', '')
FROM SourceTable

SQL Server 2017 introduced the function TRANSLATE where you can specifiy a list of characters to be replaced
SELECT TRANSLATE('MAX(0,MIN(h-36,8))', '(,-)', ' ') -->'MAX 0 MIN h 36 8 '

Related

SQL Server removing necessary whitespaces

I'm trying to add whitespaces to a column. However, the SPACE function is not working.
Example:
SELECT LEN(('ABC' + SPACE(10)))
Returns 3 instead 13.
This behavior also happens with the REPLICATE function.
Example:
REPLICATE(' ', 5)
Returns ''
What I need:
REPLICATE(' ', 5)
Returns ' '
Editing:
This suggestion works, but it needs do add : to the string.
DECLARE #Test varchar(32);
SELECT #Test = 'ABC' + SPACE(10);
SELECT #Test + ':';
Returns ABC :
I need ABC
--This table is in SQL Server
CREATE TABLE Iten
(
Code varchar(35)
);
--This table is on DB2
CREATE TABLE Product
(
code char(35),
description varchar(100)
)
INSERT INTO Iten VALUES ('ABC');
INSERT INTO Product VALUES ('ABC', 'My Test')
SELECT
Iten.Code, Product.description,
DATALENGTH(Iten.Code),
DATALENGTH(Product.code)
FROM
Iten
INNER JOIN
IBMServerD.DatabaseD.LDAT.Product AS Product ON Iten.Code = Product.code
This query returns no rows.
Because that, I need to fill spaces on the right to Iten.Code, but it does not respect it.
If both tables were in SQL Server, it would work fine.
Try using trim functions
SELECT Iten.Code, Product.description, DataLength(Iten.Code),
DataLength(Product.code)
from Iten INNER JOIN IBMServerD.DatabaseD.LDAT.Product as Product
ON ltrim(rtrim(Iten.Code)) = ltrim(rtrim(Product.code))
'ABC' + REPLICATE(' ',10)
works
SPACE(INTEGER) is working fine
select LEN('abc'+SPACE(10)) `3`
LEN() function excludes trailing blanks/whitespaces
select DATALENGTH('abc'+SPACE(10)) `13`
using DATALENGTH() give you 13, DATALENGTH() includes trailing blanks/whitespaces

Multiple occurrences of a character match using regular expression in sql server 2014

In SQL Server 2014, i want to select a row which contains a word that is not present inside any of the angled brackets <>.
Sample Data:
Row 1 --> <div class="highlight"><b>Maddy</b></div>
Row 2 --> <div><b>This is highlighting an feature.</b></div>"
Here i want to filter only second row. So i used a query like
select * from table where column like '%<%>[a-zA-z0-9]*'+'highlight'+'%<%>%'"
I believe this is what you need:
LIKE 'T%[a-z]%[a-z]%'
Now would be a good time to familiarize yourself with what you can and cannot do with the LIKE operator.
Attempt:
select * from table_name where column_name like 'T[a-z]%'
select * from table_name where column_name like '[T]%'
You've nearly had the answer yourself Mathan.
The only problem that I can see with your code is that you were treating the LIKE expression as a dynamic expression.
If you are searching for a specific value in the middle of a substring then you need to wrap it in wildcards, even if you are joining search expressions together, e.g. LIKE '%highlight% + '%<%>%'
DECLARE #table table ( [column] varchar(100));
insert into #table ([column])
SELECT * FROM
(
VALUES
('<div class="highlight"><b>Maddy</b></div>'),
('<div><b>This is highlighting an feature.</b></div>')
) as [table] ([column]);
--SELECT * FROM #table;
select
[text_value] = PATINDEX('%<div>%', [column]) + LEN('<div>'),
SUBSTRING(
[column] -- what you're searching
, PATINDEX('%<div>%', [column]) + LEN('<div>') -- after the '<div>',
-- need to add the length of the 'div' as PATINDEX returns the starting location
, PATINDEX('%</div>%', [column]) - LEN('</div>') -- until the '</div>'
)
, *
from #table
where [column] like
'%<%>[a-zA-z0-9]%' -- you need to end these with the wildcard
+'%highlight%' -- or SQL-Server thinks it's the end of the sentence
+'%<%>%';
EDIT:
Adding in the PATINDEX can be used to remove the '<>' from the string. Example above removes the <div></div> but you can use that to remove any others as necessary e.g. <b></b>

Cannot find letter 'ș' or 'Ș' inserted from Romanian (Standard) keyboard

I have a table in sql server 2012, where one column is nvarchar. It contains Romanian characters. We've noticed that only some of the letters 'Ș' do not show in reports at all, so I found that it depends of the keyboard settings.
There are two different keyboard settings for Romanian - Standard and Legacy. Letter 'Ș' - inserted from Rom(Standard) keyboard have ASCII code 63, from Legacy it's 170.
Letter 'Ş' with CHAR(170) - shows in reports, but CHAR(63) - doesn't - even though it's the same letter (should be).
It would be simple if I could replace char(63) with char(170), but I cannot detect rows with character 63. The next select doesn't return rows:
select * from table1 where columnname like '%'+CHAR(63)+'%'
even though if I do select ASCII(SUBSTRING(columnname , 1, 1)) it returns me '63'.
even select charindex(char(63), columnname) - returns me 0
I also tried to do collation:
select * from table1 where columnname COLLATE Latin1_general_CI_AI like N'%s%'
it doesn't help - it returns only rows with 's' and char(170).
Please help me find these rows with wrong 'Ş'
So firstly from my comments, CHAR(63) is misleading as it represents a character that sql server is unable to display:
Unable to replace Char(63) by SQL query
The issue is possibly down to your selected collation, as if I run this sample I get the 2 rows containing the special characters:
CREATE TABLE #temp ( val NVARCHAR(50) )
INSERT INTO #temp
( val )
VALUES ( N'Șome val 1' ),
( N'some val 2' ),
( N'șome other val 3' )
SELECT *
FROM #temp
WHERE val COLLATE Latin1_General_BIN LIKE N'%ș%'
OR val COLLATE Latin1_General_BIN LIKE N'%Ș%'
DROP TABLE #temp
Output
val
=================
Șome val 1
șome other val 3
The specified collation is: Latin1_General_BIN, as found in this post:
replace only matches the beginning of the string
WHERE columnname LIKE N'%'+NCHAR(536)+'%'
This should help you find the character even if it was inserted as an unknown character as in the first insert below.
DECLARE #Table TABLE (text nvarchar(50))
INSERT INTO #Table(text)
SELECT 'Ș'
UNION ALL
SELECT N'Ș'
SELECT UNICODE(text) UNICODE
FROM #Table
Results:
UNICODE
63
536
'Ș' is NCHAR(536) and 'ș' is NCHAR(537).
If you then do:
SELECT * FROM #Table WHERE text LIKE N'%'+NCHAR(536)+'%'
Results:
text
?
Ș

LIKE with Multiple Consecutive White Spaces

I have following query with LIKE predicate in SQL Server 2012. It replaces white spaces with %. I have two records in the table.
DECLARE #MyTable TABLE (ITMEID INT, ITMDESC VARCHAR(100))
INSERT INTO #MyTable VALUES (1,'Healty and Alive r')
INSERT INTO #MyTable VALUES (2, 'A liver patient')
DECLARE #SearchCriteria VARCHAR(100)
SET #SearchCriteria = 'Alive'
SELECT *
FROM #MyTable
WHERE (ITMDESC LIKE '%'+REPLACE(#SearchCriteria,' ','%')+'%' ESCAPE '\')
I got this query from a friend to consider multiple consequent white spaces as a single space. The challenge is I don't see any reference for this.
Is there a pitfall in the approach?
REPLACE(#SearchCriteria,' ','%') always returns Alive. There is no Alive word in the second row, therefore it's not returned.
In fact, WHERE clause will look like this: WHERE (ITMDESC LIKE '%Alive%' ESCAPE '\')
The second row doesn't meet it.
Probably, you want something like this:
SELECT *
FROM #MyTable
WHERE (REPLACE(ITMDESC,' ','') LIKE '%'+#SearchCriteria+'%' ESCAPE '\')
you can use as below
DECLARE #MyTable TABLE (ITMEID INT, ITMDESC VARCHAR(100))
INSERT INTO #MyTable VALUES (1,'Healty and Alive r')
INSERT INTO #MyTable VALUES (2, 'A liver patient')
ECLARE #SearchCriteria VARCHAR(100)
SET #SearchCriteria = 'Alive'
SELECT *
FROM #MyTable
WHERE (REPLACE(ITMDESC,' ','') LIKE '%'+#SearchCriteria+'%' ESCAPE '\')
it will return both records as you want
The simplest solution is to replace all spaces with some moniker and then replace that moniker with a single space.
Select Replace(Replace(ItmDesc, ' ', '<z>'), '<z>', ' ')
From MyTable
SQL Fiddle version

What is the simplest/best way to remove substrings at the end of a string?

I have a function that normalizes addresses. What I would like to do now is remove any of the strings in a limited, specified list if they occur at the end of the string. Let's say the strings I want to remove are 'st', 'ave', 'rd', 'dr', 'ct'... If the string ends with any of these strings, I want to remove them. What is the best way to accomplish this, using T-SQL (this will not be part of a select statement)?
Edit:
This is a function that accepts one address and formats it. I would like to inline the code, and the list, but in the simplest way possible. For example, some code that I've been playing with is:
if #address LIKE '%st'
SET #address = substring(#address, 1, PatIndex('%st', #address) - 1)
Is this a good method? How can I put it in some sort of loop so I can repeat this code with different values (other than st)?
Adding the values to be trimmed to a new table allows you to
easily add new values
use this table to clean up adresses
SQL Statement
DECLARE #Input VARCHAR(32)
SET #Input = 'Streetsstaverddrad'
DECLARE #Trim TABLE (Value VARCHAR(32))
INSERT INTO #Trim
SELECT 'st'
UNION ALL SELECT 'ave'
UNION ALL SELECT 'rd'
UNION ALL SELECT 'dr'
UNION ALL SELECT 'ad'
WHILE EXISTS (
SELECT *
FROM (
SELECT [Adres] = #Input
) i
INNER JOIN #Trim t ON i.Adres LIKE '%' + t.Value
)
BEGIN
SELECT #Input = SUBSTRING(Adres, 1, LEN(Adres) - LEN(t.Value))
FROM (
SELECT [Adres] = #Input
) i
INNER JOIN #Trim t ON i.Adres LIKE '%' + t.Value
END
SELECT #Input
In SQL Server 2005 it is possible to define a user-function which enables regular expression matching. You will need to defined a function which strips the trailing strings. A RegEx to match the scenarios you mention would be something like...
\s+(ave|rd|dr|ct)\s*$