Remove ALL white spaces in a string sql server - sql-server

I'm trying to convert this '232431 K' into this '232431K' and I can't find a function that does this. All the references I have found are TRIM, RTRIM and LTRIM but these functions are not useful for me in this case because I don't have left or right white spaces to be removed, the white spaces are "inside" the string.

You can refer to Remove all spaces from a string in SQL Server.
In simple terms, you will need to use REPLACE function, such as REPLACE(stringValue, ' ', '')

In addition to using replace, on SQL Server 2017+ to avoid multiple nested functions, you can use translate if there are multiple characters in a string you want to remove:
Remove space, hyphen, slash:
declare #string varchar(50)='12345 67-9\x'
select Replace(Translate(#string, ' -\','???'),'?','')

Maybe try REPLACE like below
SELECT REPLACE(N'232431 K',' ','')
As asked in another comment
What if I have to replace ' ' or '-', is it possible to put it all using just one REPLACE function? For example REPLACE(stringValue, [' ', '-'], '')
you should use replace in conjuction with Translate function
select replace(translate (N'l;[pi-',';[-',' '),' ','')

Related

How do I remove line feed characters when selecting data from SQL Server?

I insert data that contains a line feed character into the database. Then I retrieve that data. I am using this script to attempt to remove the line feed while selecting the data from SQL:
Select Replace(Replace stringname,char(10),'',char(32),'')) from tablename
The replace function seems to execute, but it does not remove the line feed correctly.
The syntax of your statment looks wrong, maybe you can try with something like this:
Select Replace(Replace(#str,CHAR(10),''),CHAR(13),'')
The inner replace relaces LF and the outer replace replace CR
Shouldn't it be Select Replace(Replace(stringname,char(10),''),char(13),'') from tablename?
Also you could use single replace Select Replace(stringname,char(13)+char(10),'') from tablename.
char(32) corresponds to a space symbol
(select Replace( (select REPLACE( ColName,CHAR(10),'')),char(13),''))
as ColAlias
from YourTable
Solved with following .
I had issues with in sql data which even can not be seen as well in sql, causing me problem in some jquery functions.
A line feed is CHAR(10); a carriage return is CHAR(13).
The following code will remove a line feed characters and replaces it with a zero-length string:
UPDATE Table_Name SET Field_Name = REPLACE(Field_Name,CHAR(10),'');
If you want remove CRLF from the end of a string you can use RTRIM in postgresql.
for update operation:
UPDATE tablename
SET columnname = RTRIM(RTRIM(columnname,chr(10)),chr(13))
WHERE columnname like '%' || chr(13) or columnname like '%' || chr(10)
or for select:
SELECT RTRIM(RTRIM(columnname,chr(10)),chr(13)) FROM tablename
if you want leading or both use LTRIM or BTRIM

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

I'm in the process of trying to clear out leading and trailing spaces from an NVARCHAR(MAX) column that is filled with prices (using NVARCHAR due to data importing from multiple operating systems with odd characters).
At this point I have a t-sql command that can remove the leading/trailing spaces from static prices. However, when it comes to leveraging this same command to remove all prices, I'm stumped.
Here's the static script I used to remove a specific price:
UPDATE *tablename* set *columnname* = LTRIM(RTRIM(2.50)) WHERE cost = '2.50 ';
Here's what I've tried to remove all the trailing spaces:
UPDATE *tablename* set *columnname* LIKE LTRIM(RTRIM('[.]')) WHERE cost LIKE '[.] ';
I've also tried different varations of the % for random characters but at this point I'm spinning my wheels.
What I'm hoping to achieve is to run one simple command that takes off all the leading and trailing spaces in each cell of this column without modifying any of the actual column data.
To remove spaces from left/right, use LTRIM/RTRIM. What you had
UPDATE *tablename*
SET *columnname* = LTRIM(RTRIM(*columnname*));
would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been
UPDATE [tablename]
SET [columnname] = LTRIM(RTRIM([columnname]))
WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));
Note: 32 is the ascii code for the space character.
To remove spaces... please use LTRIM/RTRIM
LTRIM(String)
RTRIM(String)
The String parameter that is passed to the functions can be a column name, a variable, a literal string or the output of a user defined function or scalar query.
SELECT LTRIM(' spaces at start')
SELECT RTRIM(FirstName) FROM Customers
Read more: http://rockingshani.blogspot.com/p/sq.html#ixzz33SrLQ4Wi
LTrim function and RTrim function :
The LTrim function to remove leading spaces and the RTrim
function to remove trailing spaces from a string variable.
It uses the Trim function to remove both types of spaces.
select LTRIM(RTRIM(' SQL Server '))
output:
SQL Server
I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim directly as below:
UPDATE *tablename*
SET *columnname* = trim(*columnname*);
SELECT RTRIM(' Author ') AS Name;
Output will be without any trailing spaces.
Name
——————
‘ Author’
The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable.
It uses the Trim function to remove both types of spaces and means before and after spaces of string.
SELECT LTRIM(RTRIM(REVERSE(' NEXT LEVEL EMPLOYEE ')))

Escape Character in SQL Server

I want to use quotation with escape character. How can I do to avoid the following error when one has a special character?
Unclosed quotation mark after the character string.
You can escape quotation like this:
select 'it''s escaped'
result will be
it's escaped
To escape ' you simly need to put another before: ''
As the second answer shows it's possible to escape single quote like this:
select 'it''s escaped'
result will be
it's escaped
If you're concatenating SQL into a VARCHAR to execute (i.e. dynamic SQL), then I'd recommend parameterising the SQL. This has the benefit of helping guard against SQL injection plus means you don't have to worry about escaping quotes like this (which you do by doubling up the quotes).
e.g. instead of doing
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
EXECUTE(#SQL)
try this:
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT * FROM MyTable WHERE Field1 = #Field1'
EXECUTE sp_executesql #SQL, N'#Field1 VARCHAR(10)', 'AAA'
You can define your escape character, but you can only use it with a LIKE clause.
Example:
SELECT columns FROM table
WHERE column LIKE '%\%%' ESCAPE '\'
Here it will search for % in whole string and this is how one can use ESCAPE identifier in SQL Server.
You need to just replace ' with '' inside your string
SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'
You can also use REPLACE(#name, '''', '''''') if generating the SQL dynamically
If you want to escape inside a like statement then you need to use the ESCAPE syntax
It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or: http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F
Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.
If you want to escape user input in a variable you can do like below within SQL
Set #userinput = replace(#userinput,'''','''''')
The #userinput will be now escaped with an extra single quote for every occurance of a quote
WHERE username LIKE '%[_]d'; -- #Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';
FROM:
SQL Server Escape an Underscore
You could use the **\** character before the value you want to escape e.g
insert into msglog(recipient) values('Mr. O\'riely')
select * from msglog where recipient = 'Mr. O\'riely'
To keep the code easy to read, you can use square brackets [] to quote the string containing ' or vice versa .

Replace single quotes in SQL Server

I have this function in SQL Server to replace single quotes.
But when I insert a single quote it throws an error on Replace(#strip,''','')):
Create Function [dbo].[fn_stripsingleQuote]
(#strStrip varchar(Max))
returns varchar
as
begin
declare #CleanString varchar(Max)
SET #var=(Replace(#strip,'',''))
return #var
end
You need to double up your single quotes as follows:
REPLACE(#strip, '''', '')
Try REPLACE(#strip,'''','')
SQL uses two quotes to represent one in a string.
If you really must completely strip out the single quotes you can do this:
Replace(#strip, '''', '')
However, ordinarily you'd replace ' with '' and this will make SQL Server happy when querying the database. The trick with any of the built-in SQL functions (like replace) is that they too require you to double up your single quotes.
So to replace ' with '' in code you'd do this:
Replace(#strip, '''', '''''')
Of course... in some situations you can avoid having to do this entirely if you use parameters when querying the database. Say you're querying the database from a .NET application, then you'd use the SqlParameter class to feed the SqlCommand parameters for the query and all of this single quote business will be taken care of automatically. This is usually the preferred method as SQL parameters will also help prevent SQL injection attacks.
You could use char(39)
insert into my_table values('hi, my name'+char(39)+'s tim.')
Or in this case:
Replace(#strip,char(39),'')
Looks like you're trying to duplicate the QUOTENAME functionality. This built-in function can be used to add delimiters and properly escape delimiters inside strings and recognizes both single ' and double " quotes as delimiters, as well as brackets [ and ].
Try escaping the single quote with a single quote:
Replace(#strip, '''', '')
We have to double the number of quotes.
To replace single quote :
REPLACE(#strip, '''', '')
To replace double quotes :
REPLACE(#strip, '''''', '')
If escaping your single quote with another single quote isn't working for you (like it didn't for one of my recent REPLACE() queries), you can use SET QUOTED_IDENTIFIER OFF before your query, then SET QUOTED_IDENTIFIER ON after.
For example
SET QUOTED_IDENTIFIER OFF;
UPDATE TABLE SET NAME = REPLACE(NAME, "'S", "S");
SET QUOTED_IDENTIFIER OFF;
I ran into a strange anomaly that would apply here. Using Google API and getting the reply in XML format, it was failing to convert to XML data type because of single quotes.
Replace(#Strip ,'''','')
was not working because the single quote was ascii character 146 instead of 39.
So I used:
Replace(#Strip, char(146), '')
which also works for regular single quotes char(39) and any other special character.
Try this :
select replace (colname, char(39)+char(39), '') AS colname FROM .[dbo].[Db Name];
I have achieved the desired result.
Example : Input value --> Like '%Pat') '' OR
Want Output --> *Like '%Pat') OR*
using above query achieved the desired result.
The striping/replacement/scaping of single quotes from user input (input sanitation), has to be done before the SQL statement reaches the database.
Besides needing to escape the quote (by using double quotes), you've also confused the names of variables: You're using #var and #strip, instead of #CleanString and #strStrip...
I think this is the shortest SQL statement for that:
CREATE FUNCTION [dbo].[fn_stripsingleQuote] (#strStrip varchar(Max))
RETURNS varchar(Max)
AS
BEGIN
RETURN (Replace(#strStrip ,'''',''))
END
I hope this helps!
select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

Escape a string in SQL Server so that it is safe to use in LIKE expression

How do I escape a string in SQL Server's stored procedure so that it is safe to use in LIKE expression.
Suppose I have an NVARCHAR variable like so:
declare #myString NVARCHAR(100);
And I want to use it in a LIKE expression:
... WHERE ... LIKE '%' + #myString + '%';
How do I escape the string (more specifically, characters that are meaningful to LIKE pattern matching, e.g. % or ?) in T-SQL, so that it is safe to use in this manner?
For example, given:
#myString = 'aa%bb'
I want:
WHERE ... LIKE '%' + #somehowEscapedMyString + '%'
to match 'aa%bb', 'caa%bbc' but not 'aaxbb' or 'caaxbb'.
To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)
For example this escapes the % symbol, using \ as the escape char:
select * from table where myfield like '%15\% off%' ESCAPE '\'
If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:
set #myString = replace(
replace(
replace(
replace( #myString
, '\', '\\' )
, '%', '\%' )
, '_', '\_' )
, '[', '\[' )
(Note that you have to escape your escape char too, and make sure that's the inner replace so you don't escape the ones added from the other replace statements). Then you can use something like this:
select * from table where myfield like '%' + #myString + '%' ESCAPE '\'
Also remember to allocate more space for your #myString variable as it will become longer with the string replacement.
Had a similar problem (using NHibernate, so the ESCAPE keyword would have been very difficult) and solved it using the bracket characters. So your sample would become
WHERE ... LIKE '%aa[%]bb%'
If you need proof:
create table test (field nvarchar(100))
go
insert test values ('abcdef%hijklm')
insert test values ('abcdefghijklm')
go
select * from test where field like 'abcdef[%]hijklm'
go
Rather than escaping all characters in a string that have particular significance in the pattern syntax given that you are using a leading wildcard in the pattern it is quicker and easier just to do.
SELECT *
FROM YourTable
WHERE CHARINDEX(#myString , YourColumn) > 0
In cases where you are not using a leading wildcard the approach above should be avoided however as it cannot use an index on YourColumn.
Additionally in cases where the optimum execution plan will vary according to the number of matching rows the estimates may be better when using LIKE with the square bracket escaping syntax when compared to both CHARINDEX and the ESCAPE keyword.
You specify the escape character. Documentation here:
http://msdn.microsoft.com/en-us/library/ms179859.aspx
Do you want to look for strings that include an escape character? For instance you want this:
select * from table where myfield like '%10%%'.
Where you want to search for all fields with 10%? If that is the case then you may use the ESCAPE clause to specify an escape character and escape the wildcard character.
select * from table where myfield like '%10!%%' ESCAPE '!'
Alternative escaping syntax:
LIKE Wildcard Literals
The JDBC driver supports the {escape 'escape character'} syntax for using LIKE clause wildcards as literals.
SELECT *
FROM tab
WHERE col LIKE 'a\_c' {escape '\'};
db<>fiddle demo

Resources