SQL method to replace repeating blanks with single blanks - sql

Is there a more elegant way of doing this. I want to replace repeating blanks with single blanks....
declare #i int
set #i=0
while #i <= 20
begin
update myTable
set myTextColumn = replace(myTextColumn, ' ', ' ')
set #i=#i+1
end
(its sql server 2000 - but I would prefer generic SQL)

This works:
UPDATE myTable
SET myTextColumn =
REPLACE(
REPLACE(
REPLACE(myTextColumn
,' ',' '+CHAR(1)) -- CHAR(1) is unlikely to appear
,CHAR(1)+' ','')
,CHAR(1),'')
WHERE myTextColumn LIKE '% %'
Entirely set-based; no loops.
So we replace any two spaces with an unusual character and a space. If we call the unusual character X, 5 spaces become: ' X X ' and 6 spaces become ' X X X'. Then we replace 'X ' with the empty string. So 5 spaces become ' ' and 6 spaces become ' X'. Then, in case there was an even number of spaces, we remove any remaining 'X's, leaving a single space.

Here is a simple set based way that will collapse multiple spaces into a single space by applying three replaces.
DECLARE #myTable TABLE (myTextColumn VARCHAR(50))
INSERT INTO #myTable VALUES ('0Space')
INSERT INTO #myTable VALUES (' 1 Spaces 1 Spaces. ')
INSERT INTO #myTable VALUES (' 2 Spaces 2 Spaces. ')
INSERT INTO #myTable VALUES (' 3 Spaces 3 Spaces. ')
INSERT INTO #myTable VALUES (' 4 Spaces 4 Spaces. ')
INSERT INTO #myTable VALUES (' 5 Spaces 5 Spaces. ')
INSERT INTO #myTable VALUES (' 6 Spaces 6 Spaces. ')
select replace(
replace(
replace(
LTrim(RTrim(myTextColumn)), ---Trim the field
' ',' |'), ---Mark double spaces
'| ',''), ---Delete double spaces offset by 1
'|','') ---Tidy up
AS SingleSpaceTextColumn
from #myTable
Your Update statement can now be set based:
update #myTable
set myTextColumn = replace(
replace(
replace(
LTrim(RTrim(myTextColumn)),
' ',' |'),
'| ',''),
'|','')
Use an appropriate Where clause to limit the Update to only the rows that have you need to update or maybe have double spaces.
Example:
where 1<=Patindex('% %', myTextColumn)
I have found an external write up on this method: REPLACE Multiple Spaces with One

select
string = replace(
replace(
replace(' select single spaces',' ','<>')
,'><','')
,'<>',' ')
Replace duplicate spaces with a single space in T-SQL

SELECT 'starting...' --sets ##rowcount
WHILE ##rowcount <> 0
update myTable
set myTextColumn = replace(myTextColumn, ' ', ' ')
where myTextColumn like '% %'

Not very SET Based but a simple WHILE would do the trick.
CREATE TABLE #myTable (myTextColumn VARCHAR(32))
INSERT INTO #myTable VALUES ('NoSpace')
INSERT INTO #myTable VALUES ('One Space')
INSERT INTO #myTable VALUES ('Two Spaces')
INSERT INTO #myTable VALUES ('Multiple Spaces .')
WHILE EXISTS (SELECT * FROM #myTable WHERE myTextColumn LIKE '% %')
UPDATE #myTable
SET myTextColumn = REPLACE(myTextColumn, ' ', ' ')
WHERE myTextColumn LIKE '% %'
SELECT * FROM #myTable
DROP TABLE #myTable

Step through the characters one by one, and maintain a record of the previous character. If the current character is a space, and the last character is a space, stuff it.
CREATE FUNCTION [dbo].[fnRemoveExtraSpaces] (#Number AS varchar(1000))
Returns Varchar(1000)
As
Begin
Declare #n int -- Length of counter
Declare #old char(1)
Set #n = 1
--Begin Loop of field value
While #n <=Len (#Number)
BEGIN
If Substring(#Number, #n, 1) = ' ' AND #old = ' '
BEGIN
Select #Number = Stuff( #Number , #n , 1 , '' )
END
Else
BEGIN
SET #old = Substring(#Number, #n, 1)
Set #n = #n + 1
END
END
Return #number
END
GO
select [dbo].[fnRemoveExtraSpaces]('xxx xxx xxx xxx')

Here is a Simplest solution :)
update myTable
set myTextColumn = replace(replace(replace(LTrim(RTrim(myTextColumn )),' ','<>'),'><',''),'<>',' ')

create table blank(
field_blank char(100))
insert into blank values('yyy yyyy')
insert into blank values('xxxx xxxx')
insert into blank values ('xxx xxx')
insert into blank values ('zzzzzz zzzzz')
update blank
set field_blank = substring(field_blank,1,charindex(' ',field_blank)-1) + ' ' + ltrim(substring(field_blank,charindex(' ',field_blank) + 1,len(field_blank)))
where CHARINDEX (' ' , rtrim(field_blank)) > 1
select * from blank

For me the above examples almost did a trick but I needed something that was more stable and independent of the table or column or a set number of iterations. So this is my modification from most of the above queries.
CREATE FUNCTION udfReplaceAll
(
#OriginalText NVARCHAR(MAX),
#OldText NVARCHAR(MAX),
#NewText NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
WHILE (#OriginalText LIKE '%' + #OldText + '%')
BEGIN
SET #OriginalText = REPLACE(#OriginalText,#OldText,#NewText)
END
RETURN #OriginalText
END
GO

Lets say, your Data like this
Table name : userdata Field: id, comment, status,
id, "I love -- -- - -spaces -- - my INDIA" , "Active" <br>
id, "I love -- -- - -spaces -- - my INDIA" , "Active" <br>
id, "I love -- -- - -spaces -- - my INDIA" , "Active" <br>
id, "I love -- -- - -spaces -- - my INDIA" , "Active" <br>
So just do like this
update userdata set comment=REPLACE(REPLACE(comment," ","-SPACEHERE-"),"-SPACEHERE"," ");
I didn't tested , but i think this will work.

Try this:
UPDATE Ships
SET name = REPLACE(REPLACE(REPLACE(name, ' ', ' ' + CHAR(1)), CHAR(1) + ' ', ''), CHAR(1), '')
WHERE name LIKE '% %'

REPLACE(REPLACE(REPLACE(myTextColumn,' ',' %'),'% ',''),'%','')
Statement above worked terrifically for replacing multiple spaces with a single space. Optionally add LTRIM and RTRIM to remove spaces at the beginning.
Got it from here: http://burnignorance.com/database-tips-and-tricks/remove-multiple-spaces-from-a-string-using-sql-server/

WHILE
(SELECT count(myIDcolumn)
from myTable where myTextColumn like '% %') > 0
BEGIN
UPDATE myTable
SET myTextColumn = REPLACE(myTextColumn ,' ',' ')
END

Try it:
CREATE OR REPLACE FUNCTION REM_SPACES (TEXTO VARCHAR(2000))
RETURNS VARCHAR(2000)
LANGUAGE SQL
READS SQL DATA
BEGIN
SET TEXTO = UPPER(LTRIM(RTRIM(TEXTO)));
WHILE LOCATE(' ',TEXTO,1) >= 1 DO
SET TEXTO = REPLACE(TEXTO,' ',' ');
END WHILE;
RETURN TEXTO;
END

Update myTable set myTextColumn = replace(myTextColumn, ' ', ' ');
The above query will remove all the double blank spaces with single blank space
But this would work only once.

Related

Delete blank spaces in a string column SQL Server

I have sql table with the following values:
'test1 ', 'test2 '.
I need to delete all blank spaces in a string.
It looks easy but TRIM, LTRIM, RTRIM or REPLACE(column,' ','') does not work.
LEN() function count that space as a character.
Lenght of value 'test1 ' is 6.
In which way can I select that column without that blank space?
I need value 'test1'.
The minimal reproducible example is not provided.
Please try the following solution.
SQL
USE tempdb;
GO
DROP FUNCTION IF EXISTS dbo.udf_tokenize;
GO
/*
1. All invisible TAB, Carriage Return, and Line Feed characters will be replaced with spaces.
2. Then leading and trailing spaces are removed from the value.
3. Further, contiguous occurrences of more than one space will be replaced with a single space.
*/
CREATE FUNCTION dbo.udf_tokenize(#input VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN (SELECT CAST('<r><![CDATA[' + #input + ' ' + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)'));
END
GO
-- DDL and sample data population, start
DECLARE #mockTbl TABLE (ID INT IDENTITY(1,1), col_1 VARCHAR(100), col_2 VARCHAR(100));
INSERT INTO #mockTbl (col_1, col_2)
VALUES (' FL ', ' Miami')
, (' FL ', ' Fort Lauderdale ')
, (' NY ', ' New York ')
, (' NY ', '')
, (' NY ', NULL);
-- DDL and sample data population, end
-- before
SELECT * FROM #mockTbl;
-- remove invisible chars
UPDATE #mockTbl
SET col_1 = dbo.udf_tokenize(col_1)
, col_2 = dbo.udf_tokenize(col_2);
-- after
SELECT *, LEN(col_2) AS [col_2_len] FROM #mockTbl;
As discovered in the comments, the character(s) at the end of your value isn't a whitespace, it's a carriage return. LTRIM and RTRIM don't remove these characters, and TRIM only removes whitespace (character 32) by default.
If you want to remove some other characters, you can use TRIM, but you need to tell it to remove said other characters, using the TRIM({Characters} FROM {String}) syntax. The below removes leading and trailing Spaces (' '), Carriage Returns (CHAR(13)) and Line Breaks (CHAR(10)):
CREATE TABLE dbo.YourTable (SomeString varchar(50));
GO
INSERT INTO dbo.YourTable (SomeString)
VALUES('Trailing Space'),
('Trailing Line Break' + CHAR(10)),
('Trailing CRLF' + CHAR(13) + CHAR(10)),
('Trailing CRLF and spaces ' + CHAR(13) + CHAR(10) + ' ');
GO
DECLARE #TrimCharacters varchar(10) = ' ' + CHAR(13) + CHAR(10);
SELECT SomeString,
LEN(SomeString) AS Len,
DATALENGTH(SomeString) AS DataLength,
TRIM(SomeString) AS Trimmed,
DATALENGTH(TRIM(SomeString)) AS TrimmedDataLength,
TRIM(#TrimCharacters FROm SomeString) AS WellTrimmed,
DATALENGTH(TRIM(#TrimCharacters FROm SomeString)) AS WellTrimmedDataLength
FROM dbo.YourTable;
GO
DROP TABLE dbo.YourTable;
You can use the function below to check if each character of the string is within the ASCII values 32 to 126 (Numbers & Alphabet).
This will remove the "character" that's not within the ASCII range.
SQL:
DECLARE #TestString varchar(10) = 'test1 '
DECLARE #Result nvarchar(max)
SET #Result = ''
DECLARE #character nvarchar(1)
DECLARE #characterposition int
SET #characterposition = 1
WHILE #characterposition <= LEN(#TestString)
BEGIN
SET #character = SUBSTRING(#TestString , #characterposition, 1)
IF ASCII(#character) >= 32 AND ASCII(#character) <= 126
SET #Result = #Result + #character
SET #characterposition = #characterposition + 1
END
SELECT #Result

TSQL - Replacing or removing a string between two dissimilar strings, multiple times in a field for an entire column

I want to replace or remove all characters between and including these two characters < > they occur numerous times throughout the field and in varying circumstances for each row
I believe the strings to be replaced are html so when I tried to post an example the site just registered it as formatting.
I used replace to remove all common strings such as the the html for line break but some vary field to field using hexadecimal color values.
Thanks!
DECLARE #foo TABLE(TAGS VARCHAR(MAX));
INSERT #foo VALUES('<fname>John</fname><lname>Dewey</lname>');
SELECT 1; --This will initialize ##ROWCOUNT if necessary. Might be optional depending on your query
WHILE ##ROWCOUNT > 0 BEGIN
UPDATE #foo
SET TAGS = STUFF(TAGS,CHARINDEX('<',TAGS),CHARINDEX('>',TAGS) - CHARINDEX('<',TAGS) + 1,'')
WHERE TAGS LIKE '%<%>%'
END
SELECT * FROM #foo;
Result
------------------------
JohnDewey
CREATE TABLE #html(Value NVARCHAR(MAX))
INSERT INTO #html(Value) VALUES('<ShouldBeRemoved>1 <Remove>abc<also remove>def<Take this out>ghi')
INSERT INTO #html(Value) VALUES('<ShouldBeRemoved>2 <Remove>abc<also remove>def<Take this out>ghi')
INSERT INTO #html(Value) VALUES('<ShouldBeRemoved>3 <Remove>abc<also remove>def<Take this out>ghi')
;with Cte(Value) AS (
SELECT Value FROM #html
UNION ALL
SELECT REPLACE(Value, SUBSTRING(Value, CHARINDEX('<', Value), CHARINDEX('>', Value) - CHARINDEX('<', Value) + 1),'')
FROM Cte
WHERE CHARINDEX('<', Value) != 0
)
SELECT Value FROM Cte
WHERE CHARINDEX('<', Value) = 0
OPTION (MAXRECURSION 0);
DROP TABLE #html
CREATE FUNCTION [dbo].[udf_RemoveHtmlTag] (#HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
WHILE((CHARINDEX('<', #HTMLText)>0) and (CHARINDEX('>', #HTMLText)>0))
Begin
SET #HTMLText = REPLACE(#HtmlText,SUBSTRING(#HTMLText, CHARINDEX('<', #HTMLText), CHARINDEX('>', #HTMLText) - CHARINDEX('<', #HTMLText) + 1),'');
End
RETURN #HTMLText
END
GO
Then how to use this func
select [dbo].[udf_RemoveHtmlTag]([column_name]) from tablename
This code will work for them who wants to avoid calling UDF (User Defined Function).
Assuming that one of your sql table col. contains HTML tags like below and you want to remove everything between < and > .
[Remark] =" the HTML tags like: < div > < p >< span > We are trying to contact the company (Tel: < /span >< span> < /p > < /div > etc' "
Step#1: Store your result set to a Temp table
select .... into #t1 from....where...blah blah
Step#2: Use the following code to remove everything between < and > and update the field.
WHILE ##ROWCOUNT > 0 BEGIN
UPDATE #t1
SET [Remark] = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(STUFF([Remark],CHARINDEX('<',[Remark]),CHARINDEX('>',[Remark]) - CHARINDEX('<',[Remark]) + 1,'') )), CHAR(9), ' '), CHAR(10), ' '), CHAR(11), ' '), CHAR(12), ' '), CHAR(13), ' '), ' ', '')))
WHERE [Remark] LIKE '%<%>%'
END
Step#3: Select your desired result from Temp table
SELECT * FROM #t1

How to get rid of double quote from column's value?

Here is the table, each column value is wrapped with double quotes (").
Name Number Address Phone1 Fax Value Status
"Test" "10000000" "AB" "5555" "555" "555" "Active"
How to remove double quote from each column? I tried this for each column:-
UPDATE Table
SET Name = substring(Name,1,len(Name)-1)
where substring(Name,len(Name),1) = '"'
but looking for more reliable solution. This fails if any column has trailing white space
Just use REPLACE?
...
SET Name = REPLACE(Name,'"', '')
...
UPDATE Table
SET Name = REPLACE(Name, '"', '')
WHERE CHARINDEX('"', Name) <> 0
create table #t
(
Name varchar(100)
)
insert into #t(Name)values('"deded"')
Select * from #t
update #t Set Name = Coalesce(REPLACE(Name, '"', ''), '')
Select * from #t
drop table #t
Quick and Dirty, but it will work :-)
You could expand and write this as a store procedure taking in a table name, character you want to replace, character to replace with, Execute a String variable, etc...
DECLARE
#TABLENAME VARCHAR(50)
SELECT #TABLENAME = 'Locations'
SELECT 'Update ' + #TABLENAME + ' set ' + column_Name + ' = REPLACE(' + column_Name + ',''"'','''')'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #TABLENAME
and data_Type in ('varchar')

SQL: problem word count with len()

I am trying to count words of text that is written in a column of table. Therefor I am using the following query.
SELECT LEN(ExtractedText) -
LEN(REPLACE(ExtractedText, ' ', '')) + 1 from EDDSDBO.Document where ID='100'.
I receive a wrong result that is much to high.
On the other hand, if I copy the text directly into the statement then it works, i.e.
SELECT LEN('blablabla text') - LEN(REPLACE('blablabla text', ' ', '')) + 1.
Now the datatype is nvarchar(max) since the text is very long. I have already tried to convert the column into text or ntext and to apply datalength() instead of len(). Nevertheless I obtain the same result that it does work as a string but does not work from a table.
You're counting spaces not words. That will typically yield an approximate answer.
e.g.
' this string will give an incorrect result '
Try this approach: http://www.sql-server-helper.com/functions/count-words.aspx
CREATE FUNCTION [dbo].[WordCount] ( #InputString VARCHAR(4000) )
RETURNS INT
AS
BEGIN
DECLARE #Index INT
DECLARE #Char CHAR(1)
DECLARE #PrevChar CHAR(1)
DECLARE #WordCount INT
SET #Index = 1
SET #WordCount = 0
WHILE #Index <= LEN(#InputString)
BEGIN
SET #Char = SUBSTRING(#InputString, #Index, 1)
SET #PrevChar = CASE WHEN #Index = 1 THEN ' '
ELSE SUBSTRING(#InputString, #Index - 1, 1)
END
IF #PrevChar = ' ' AND #Char != ' '
SET #WordCount = #WordCount + 1
SET #Index = #Index + 1
END
RETURN #WordCount
END
GO
usage
DECLARE #String VARCHAR(4000)
SET #String = 'Health Insurance is an insurance against expenses incurred through illness of the insured.'
SELECT [dbo].[WordCount] ( #String )
Leading spaces, trailing spaces, two or more spaces between the neighbouring words – these are the likely causes of the wrong results you are getting.
The functions LTRIM() and RTRIM() can help you eliminate the first two issues. As for the third one, you can use REPLACE(ExtractedText, ' ', ' ') to replace double spaces with single ones, but I'm not sure if you do not have triple ones (in which case you'd need to repeat the replacing).
UPDATE
Here's a UDF that uses CTEs and ranking to eliminate extra spaces and then counts the remaining ones to return the quantity as the number of words:
CREATE FUNCTION fnCountWords (#Str varchar(max))
RETURNS int
AS BEGIN
DECLARE #xml xml, #res int;
SET #Str = RTRIM(LTRIM(#Str));
WITH split AS (
SELECT
idx = number,
chr = SUBSTRING(#Str, number, 1)
FROM master..spt_values
WHERE type = 'P'
AND number BETWEEN 1 AND LEN(#Str)
),
ranked AS (
SELECT
idx,
chr,
rnk = idx - ROW_NUMBER() OVER (PARTITION BY chr ORDER BY idx)
FROM split
)
SELECT #res = COUNT(DISTINCT rnk) + 1
FROM ranked
WHERE chr = ' ';
RETURN #res;
END
With this function your query will be simply like this:
SELECT fnCountWords(ExtractedText)
FROM EDDSDBO.Document
WHERE ID='100'
UPDATE 2
The function uses one of the system tables, master..spt_values, as a tally table. The particular subset used contains only values from 0 to 2047. This means the function will not work correctly for inputs longer than 2047 characters (after trimming both leading and trailing spaces), as #t-clausen.dk has correctly noted in his comment. Therefore, a custom tally table should be used if longer input strings are possible.
Replace the spaces with something that never occur in your text like ' $!' or pick another value.
then replace all '$! ' and '$!' with nothing this way you never have more than 1 space after a word. Then use your current script. I have defined a word as a space followed by a non-space.
This is an example
DECLARE #T TABLE(COL1 NVARCHAR(2000), ID INT)
INSERT #T VALUES('A B C D', 100)
SELECT LEN(C) - LEN(REPLACE(C,' ', '')) COUNT FROM (
SELECT REPLACE(REPLACE(REPLACE(' ' + COL1, ' ', ' $!'), '$! ',''), '$!', '') C
FROM #T ) A
Here is a recursive solution
DECLARE #T TABLE(COL1 NVARCHAR(2000), ID INT)
INSERT #T VALUES('A B C D', 100)
INSERT #T VALUES('have a nice day with 7 words', 100)
;WITH CTE AS
(
SELECT 1 words, col1 c, col1 FROM #t WHERE id = 100
UNION ALL
SELECT words +1, right(c, len(c) - patindex('% [^ ]%', c)), col1 FROM cte
WHERE patindex('% [^ ]%', c) > 0
)
SELECT words, col1 FROM cte WHERE patindex('% [^ ]%', c) = 0
You should declare the column using the varchar data type, like:
create table emp(ename varchar(22));
insert into emp values('amit');
select ename,len(ename) from emp;
output : 4

SQL Server 2008: How to find trailing spaces

How can I find all column values in a column which have trailing spaces? For leading spaces it would simply be
select col from table where substring(col,1,1) = ' ';
You can find trailing spaces with LIKE:
SELECT col FROM tbl WHERE col LIKE '% '
SQL Server 2005:
select col from tbl where right(col, 1) = ' '
As a demo:
select
case when right('said Fred', 1) = ' ' then 1 else 0 end as NoTrail,
case when right('said Fred ', 1) = ' ' then 1 else 0 end as WithTrail
returns
NoTrail WithTrail
0 1
This is what worked for me:
select * from table_name where column_name not like RTRIM(column_name)
This will give you all the records that have trailing spaces.
If you want to get the records that have either leading or trailing spaces then you could use this:
select * from table_name where column_name not like LTRIM(RTRIM(column_name))
A very simple method is to use the LEN function.
LEN will trim trailing spaces but not preceeding spaces, so if your LEN() is different from your LEN(REVERSE()) you'll get all rows with trailing spaces:
select col from table where LEN(col) <> LEN(REVERSE(col));
this can also be used to figure out how many spaces you have for more advanced logic.
SELECT * FROM tbl WHERE LEN(col) != DATALENGTH(col)
Should work also.
There's a few different ways to do this...
My favorite option, assuming your intention is to remove any leading and / or trailing spaces, is to execute the following, which will dynamically create the T-SQL to UPDATE all columns with an unwanted space to their trimmed value:
SELECT
'UPDATE [<DatabaseName>].[dbo].['+TABLE_NAME+']
SET ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']))
WHERE ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']));'+CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<TableName>%'
AND DATA_TYPE!='date'
ORDER BY TABLE_NAME,COLUMN_NAME
If you really need to identify them though, try one of these queries:
SELECT *
FROM [database].[schema].[table]
WHERE [col1]!=LTRIM(RTRIM([col1]))
More dynamic SQL:
SELECT 'SELECT ''['+TABLE_NAME+'].['+COLUMN_NAME+']'',*
FROM [<your database name>].[dbo].['+TABLE_NAME+']
WHERE ['+COLUMN_NAME+'] LIKE ''% ''
OR ['+COLUMN_NAME+'] LIKE '' %'';
GO
'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<filter table name as desired>%'
AND DATA_TYPE!='date'
Here's an alternative to find records with leading or trailing whitespace, including tabs etc:
SELECT * FROM tbl WHERE NOT TRIM(col) = col
Try this:
UPDATE Battles
SET name = CASE WHEN (LEN(name+'a')-1)>LEN(RTRIM(name))
THEN REPLICATE(' ', (LEN(name+'a')-1)- LEN(RTRIM(name)))+RTRIM(name)
ELSE name
END
Spaces are ignored in SQL Server so for me even the leading space was not working .
select col from table where substring(col,1,1) = ' '
wont work if there is only one space (' ') or blank ('')
so I devised following:
select * from [table] where substring(REPLACE(col, ' ', '#'),1,1) = '#'
Here is another alternative for trailing spaces.
DECLARE #VALUE VARCHAR(50) = NULL
DECLARE #VALUE VARCHAR(50) = ' '
IF ((#VALUE IS NOT NULL) AND (LTRIM(RTRIM(#VALUE)) != ''))
BEGIN
SELECT 'TRUE'
END
ELSE
BEGIN
SELECT 'FALSE'
END
I have found the accepted answer a little bit slower:
SELECT col FROM tbl WHERE col LIKE '% ';
against this technique:
SELECT col FROM tbl WHERE ASCII(RIGHT([value], 1)) = 32;
The idea is to get the last char, but compare its ASCII code with the ASCII code of space instead only with ' ' (space). If we use only ' ' space, an empty string will yield true:
DECLARE #EmptyString NVARCHAR(12) = '';
SELECT IIF(RIGHT(#EmptyString, 1) = ' ', 1, 0); -- this returns 1
The above is because of the Microsoft's implementation of string comparisons.
So, how fast exactly?
You can try the following code:
CREATE TABLE #DataSource
(
[RowID] INT PRIMARY KEY IDENTITY(1,1)
,[value] NVARCHAR(1024)
);
INSERT INTO #DataSource ([value])
SELECT TOP (1000000) 'text ' + CAST(ROW_NUMBER() OVER(ORDER BY t1.number) AS VARCHAR(12))
FROM master..spt_values t1
CROSS JOIN master..spt_values t2
UPDATE #DataSource
SET [value] = [value] + ' '
WHERE [RowID] = 100000;
SELECT *
FROM #DataSource
WHERE ASCII(RIGHT([value], 1)) = 32;
SELECT *
FROM #DataSource
WHERE [value] LIKE '% ';
On my machine there is around 1 second difference:
I have test it on table with 600k rows, but larger size, and the difference was above 8 seconds. So, how fast exactly will depend on your real case data.
Another way to achieve this by using CHARINDEX and REVERSE like below:
select col1 from table1
WHERE charindex(' ', reverse(col1)) = 1
See example Here
Simple use below query to get values having any number of spaces in begining or at end of values in column.
select * from table_name where column_name like ' %' or column_name like '% ';
We can try underscore to find the entries which are blanks,though not an accurate solution like using '% %' or ' ', But I could find entries which are blanks.
select col_name from table where col_name like '_'