Remove white spaces from string in sql - sql

SELECT CONVERT(DECIMAL(18,2)
,ROUND( REPLACE
(
REPLACE(
SUBSTRING([ColumnName],0, CHARINDEX(' ',[ColumnName],1) )
,'$',''
)
,',',''
)
,2
)
) AS 'ColumnName'
,[ColumnName]
,*
FROM TABLENAME
The CHARINDEX returns index of space, but when there is no space in data it returns 0. What I want is when ever there is a white space at the end data, SUBSTRING should consider that and when there is no white space then it should consider the length of the string.

It seems to you are working with SQL Server, then i would like to apply case expression
case when CHARINDEX(' ',[ColumnName],1) > 0
then CHARINDEX(' ',[ColumnName],1)
else len([ColumnName]) end

Apparently you're working with sql-server and want to convert a string like $123,456,789.99 to a DECIMAL.
TRY_PARSE should get you the result you want:
SELECT
TRY_PARSE(REPLACE('$123,456,789.99 ', '$', '')
AS DECIMAL(18,2)
USING 'en-US') AS myDecimalNumber
Or if it's an option for you to work with the MONEY data-type you can omit the REPLACE:
SELECT
TRY_PARSE('$123,456,789.99 '
AS MONEY
USING 'en-US')) AS myDecimalNumber

Related

SQL Server : remove "decimals" from nvarchar

I have some data that has come in as a nvarchar. Clearly the data was originally converted from a numeric based datatype. For example I have values that are 17.0000000. I would like to remove these trailing zeros so that it is just "17". I do need the output in either varchar or nvarchar.
You can get rid of the decimal and zeros afterwards using:
select (case when col like '%.0%' and col not like '%.%[^0]%'
then left(col, charindex('.', col) - 1)
when col like '%.%0'
then replace(rtrim(replace(col, '0', ' ')), ' ', '0')
else col
end)
Note: This assumes that the value is strictly numeric (hence doesn't have its own spaces).
However, I would suggest that you convert the value to an appropriate numeric/decimal type.
Yet another option if 2012+
Example
Declare #YourTable Table ([StrValue] varchar(50))
Insert Into #YourTable Values
('17.00000')
,('17.10000')
,('.1')
,('.0')
,('Cat')
,('07/29/2017')
Select *
,NewVal = coalesce(convert(varchar(50),try_convert(float,StrValue)),StrValue)
From #YourTable
Returns
StrValue NewVal
17.00000 17
17.10000 17.1
.1 0.1
.0 0
Cat Cat
07/29/2017 07/29/2017
A double cast will also get rid of the trailing zeros
select cast(cast('17.0000000' as float) as varchar)
union
select cast(cast('17.1000000' as float) as varchar)
results in
17
17.1
SELECT LEFT('17.0000000',CHARINDEX('17.0000000','.')-1)
I've hardcoded the value here but you would replace that with your column name
Another way with out using case can be:
select col
, reverse( -- use reverse to find from right
substring(
reverse(col),
patindex( -- finding first char that is not `0`
'%[^0]%',
reverse(col)) +
patindex( -- finding first char that is not `.` after removing trailing `0`s
'%[^.]%',
substring( -- remove trailing `0`s
reverse(col),
patindex('%[^0]%', reverse(col)),
len(col)) + 'x') - 1, -- Note: I add `'x'` to avoid error
len(col)))
from t;
SQL Server Fiddle Demo

Convert VarChar to Float with different culture format

From different external sources I get data where some numbers are in a NVarChar field. Until now I used a REPLACE with a CAST to ensure that numbers with a "," where cast the right way. Like this:
select cast(replace('12,5',',','.') as float)
select cast(replace('12.5',',','.') as float)
This has worked just fine, but now I get data where there is also a thousand separator in. Like this:
select cast(replace('2.012,5',',','.') as float)
select cast(replace('2,012.5',',','.') as float)
It' broken.
Is there a way to detect which data format is used in a NVarChar with a number?
I have tried to use TRY_PARSE with a culture parameter, it works well if there is a thousand separator but not without:
SELECT #Fuelunits =
CASE
WHEN ISNUMERIC(TRY_PARSE(#Hoeveelheid AS decimal(9,2) USING 'nl-NL')) = 1
THEN CAST(TRY_PARSE(#Hoeveelheid AS decimal(9,2) USING 'nl-NL') AS FLOAT)
ELSE CAST(TRY_PARSE(#Hoeveelheid AS decimal(9,2) USING 'en-US') AS FLOAT)
END
The problem is that I have to use this in an UPDATE and that that the data format can differ in the same table.
Any suggestions?
You can use CHARINDEX() to work out what separators are present and where they are in the string along with a CASE expression to handle different cases before you REPLACE and CAST to FLOAT:
CREATE TABLE #vals (val NVARCHAR(10));
INSERT INTO #vals
(
val
)
VALUES
(N'2.012,5'),
(N'2,012.5');
SELECT CAST(CASE
-- is there a '.' in a position before a ','?
WHEN CHARINDEX('.', val) < CHARINDEX(',', val) THEN
-- yes - remove the '.' and replace the ',' with '.'
REPLACE(REPLACE(val, '.', ''), ',', '.')
ELSE
-- no - just remove the ','
REPLACE(v.val, ',', '')
END AS FLOAT)
FROM #vals AS v;
DROP TABLE #vals;
References:
CHARINDEX (Transact-SQL)
Searches an expression for another expression and returns its starting position if found.

Trimming empty string or spaces in SQL

What happens when you try and trim an empty string or a bunch of spaces in SQL Server? Does it become null or ''?
trimming will only leave you with a blank space.
ltrim(rtrim(' '))
but
nullif(ltrim(rtrim(' ')),'') will give you null
Here's an easy way to test string manipulations, manually throw some strings together and find out:
;with cte as (SELECT ' 0 ' AS col
UNION SELECT ' ' AS col
)
SELECT LTRIM(RTRIM(col)) as col
FROM cte
Which returns a zero and a blank string. To get a NULL you'd have to use NULLIF()
I run this command while updating all row.
Revise your need.
For example:
UPDATE TableName SET ColumnName = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(ColumnName, CHAR(10), CHAR(32)), CHAR(13), CHAR(32)), CHAR(160), CHAR(32)),CHAR(9),CHAR(32))))

What is the most efficient way to RTRIM a STRING without using RTRIM in SQL Server 2005?

In a single-select-statement, I have the need to RTRIM a string in a SQL Server 2005 environment.
What is, in your opinion, the most efficient technique to achieve this?
Examples:
'ALPHA ' ==> 'ALPHA' (the blanks at the end are removed)
' BETA ' ==> ' BETA' (the blank in first position remains, the two blanks at the end are removed)
' GAMMA' ==> ' GAMMA' (the blank in first position remains)
Thank you in advance for your kind help.
EDIT: I am not authorized to use RTRIM!!
Try this
Declare #str Varchar(50) = ' GAMMA '
;With Cte As
(
Select Data = Substring(#str,Number,1)
From master.dbo.spt_values
where Number Between 1 And Len(#str) And Type='P'
)
Select Data = Replace(Bar,' ',' ')
From (Select Cast(Data As Varchar(Max)) From Cte For Xml Path(''))Foo(Bar)
Result
Data
GAMMA
One way as LEN(CHAR_FIELD_OR_VAR) ignores trailing spaces;
left(fld, len(fld))
or
select left(fld, (len(fld + '.')-1)-patindex('%[^ ]%', reverse(fld))+1)
Select rtrim(ltrim(col)) from....
That will trim both sides of the column
I think your answer is in the title:
SELECT Columm1
, RTRIM(Column1) as Column1Trimmed
FROM Table1
RTRIM is the most efficient method of Right TRIMming.
Without RTRIM:
select '* *'
, REPLACE('* *',' ','')

How can I remove leading and trailing quotes in SQL Server?

I have a table in a SQL Server database with an NTEXT column. This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes.
For example:
"this is a test message"
should become
this is a test message
I know of the LTRIM and RTRIM functions but these workl only for spaces. Any suggestions on which functions I can use to achieve this.
I have just tested this code in MS SQL 2008 and validated it.
Remove left-most quote:
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 2, LEN(FieldName))
WHERE LEFT(FieldName, 1) = '"'
Remove right-most quote: (Revised to avoid error from implicit type conversion to int)
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 1, LEN(FieldName)-1)
WHERE RIGHT(FieldName, 1) = '"'
I thought this is a simpler script if you want to remove all quotes
UPDATE Table_Name
SET col_name = REPLACE(col_name, '"', '')
You can simply use the "Replace" function in SQL Server.
like this ::
select REPLACE('this is a test message','"','')
note: second parameter here is "double quotes" inside two single quotes and third parameter is simply a combination of two single quotes. The idea here is to replace the double quotes with a blank.
Very simple and easy to execute !
My solution is to use the difference in the the column values length compared the same column length but with the double quotes replaced with spaces and trimmed in order to calculate the start and length values as parameters in a SUBSTRING function.
The advantage of doing it this way is that you can remove any leading or trailing character even if it occurs multiple times whilst leaving any characters that are contained within the text.
Here is my answer with some test data:
SELECT
x AS before
,SUBSTRING(x
,LEN(x) - (LEN(LTRIM(REPLACE(x, '"', ' ')) + '|') - 1) + 1 --start_pos
,LEN(LTRIM(REPLACE(x, '"', ' '))) --length
) AS after
FROM
(
SELECT 'test' AS x UNION ALL
SELECT '"' AS x UNION ALL
SELECT '"test' AS x UNION ALL
SELECT 'test"' AS x UNION ALL
SELECT '"test"' AS x UNION ALL
SELECT '""test' AS x UNION ALL
SELECT 'test""' AS x UNION ALL
SELECT '""test""' AS x UNION ALL
SELECT '"te"st"' AS x UNION ALL
SELECT 'te"st' AS x
) a
Which produces the following results:
before after
-----------------
test test
"
"test test
test" test
"test" test
""test test
test"" test
""test"" test
"te"st" te"st
te"st te"st
One thing to note that when getting the length I only need to use LTRIM and not LTRIM and RTRIM combined, this is because the LEN function does not count trailing spaces.
I know this is an older question post, but my daughter came to me with the question, and referenced this page as having possible answers. Given that she's hunting an answer for this, it's a safe assumption others might still be as well.
All are great approaches, and as with everything there's about as many way to skin a cat as there are cats to skin.
If you're looking for a left trim and a right trim of a character or string, and your trailing character/string is uniform in length, here's my suggestion:
SELECT SUBSTRING(ColName,VAR, LEN(ColName)-VAR)
Or in this question...
SELECT SUBSTRING('"this is a test message"',2, LEN('"this is a test message"')-2)
With this, you simply adjust the SUBSTRING starting point (2), and LEN position (-2) to whatever value you need to remove from your string.
It's non-iterative and doesn't require explicit case testing and above all it's inline all of which make for a cleaner execution plan.
The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].
-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters
-- (from the 2nd character and the LEN([Description]) - 2th character)
UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'
You can use following query which worked for me-
For updating-
UPDATE table SET colName= REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') WHERE...
For selecting-
SELECT REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') FROM TableName
you could replace the quotes with an empty string...
SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
LeadingAndTrailingRemoved = CASE
WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
ELSE MyTest
END
FROM MyTable
Some UDFs for re-usability.
Left Trimming by character (any number)
CREATE FUNCTION [dbo].[LTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(LTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Right Trimming by character (any number)
CREATE FUNCTION [dbo].[RTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Note the dummy character '¦' (Alt+0166) cannot be present in the data (you may wish to test your input string, first, if unsure or use a different character).
To remove both quotes you could do this
SUBSTRING(fieldName, 2, lEN(fieldName) - 2)
you can either assign or project the resulting value
You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test
CREATE FUNCTION dbo.TRIM(#String VARCHAR(MAX), #Char varchar(5))
RETURNS VARCHAR(MAX)
BEGIN
RETURN SUBSTRING(#String,PATINDEX('%[^' + #Char + ' ]%',#String)
,(DATALENGTH(#String)+2 - (PATINDEX('%[^' + #Char + ' ]%'
,REVERSE(#String)) + PATINDEX('%[^' + #Char + ' ]%',#String)
)))
END
GO
Select dbo.TRIM('"this is a test message"','"')
Reference : http://raresql.com/2013/05/20/sql-server-trim-how-to-remove-leading-and-trailing-charactersspaces-from-string/
I use this:
UPDATE DataImport
SET PRIO =
CASE WHEN LEN(PRIO) < 2
THEN
(CASE PRIO WHEN '""' THEN '' ELSE PRIO END)
ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"',
SUBSTRING(PRIO, 2, LEN(PRIO) - 2))
END
Try this:
SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
FROM TableName