I'm trying to insert trailing spaces into a VARCHAR(50) column and the SQL insert seems to be cutting them off. Here's my code:
create table #temp (field varchar(10));
insert into #temp select ' ';
select LEN(field) from #temp;
Unfortunately, this returns a length of zero, meaning the ' ' was inserted as a ''. I need a blank space to be inserted for this column - any ideas?
Use DATALENGTH, not LEN, because LEN doesn't process spaces.
Take this zero length string, for example:
SELECT LEN(' ') AS len,
DATALENGTH(' ') AS datalength
Results:
len datalength
-----------------
0 1
From http://msdn.microsoft.com/en-us/library/ms190329.aspx:
LEN Returns the number of characters of the specified string expression, excluding trailing blanks.
You better be aware also that SQL Server follows ANSI/ISO SQL-92 padding the character strings used in comparisons so that their lengths match before comparing them. So, you may want to use LIKE predicate for comparisons [1]
[1]
How SQL Server Compares Strings with Trailing Spaces
http://support.microsoft.com/kb/316626
Related
This question already has answers here:
Why the SQL Server ignore the empty space at the end automatically?
(2 answers)
Closed 4 years ago.
I want to find out the records in which a certain column contains exactly one space and nothing else. So I wrote the first of the following queries:
select COUNT(*)
from mytable
where col = ' ' -- One space
select COUNT(*)
from mytable
where col = ' ' -- Two spaces
select COUNT(*)
from mytable
where col = ' ' -- Three spaces
However, all three queries return the exact same records. Does Microsoft SQL Server not distinguish between the amount of spaces? How can I query exactly for one, two or more spaces?
Yes, it ignores trailing spaces in comparisons.
You can try to append a delimiting character.
SELECT count(*)
FROM mytable
WHERE col + 'X' = ' X';
You can combine DATALENGTH clause with your query:
select COUNT(*)
from mytable
where col = ' '
and DATALENGTH(col) = 1
The link posted by Ivan Starostin in the comments of the OP provides a good explanation and I think it deserves a full answer instead of just a comment.
To summarize, try using LIKE instead of equality:
select COUNT(*)
from mytable
where col LIKE ' ' -- one space
And you can also use DATALENGTH to calculate how many bytes are in the field to double-check field length:
select col, DATALENGTH(col)
from mytable;
Please note that DATALENGTH will return a different value if col is a VARCHAR vs NVARCHAR. VARCHAR stores each character as 1 byte where NVARCHAR stores each character as 2 bytes since NVARCHAR is stored in Unicode.
You can replace the single space with a single character (for exampe §) and then put this character in your where condition:
declare #tmp table(col varchar(50))
insert into #tmp values
(' '),
(' '),
(' ')
select COUNT(*) as one_space_count
from #tmp
where replace(col,' ','§')='§'
select COUNT(*) as two_space_count
from #tmp
where replace(col,' ','§')='§§'
select COUNT(*) as three_space_count
from #tmp
where replace(col,' ','§')='§§§'
Results:
I am using oracle 11g DB and in one of the table having varchar column has data which has trailing spaces. I have tried TRIM function to update the column but still the space at the end of the string prevails. What can be the reason for the trailing space? and how to fix this issue.
Column contents are displayed as below.
select '<'||mycol||'>' from mytab
Output : <mysamplestring >
select DUMP(mycol) from mytab
Output : Typ=1 Len=28: 67,114,117,100,101,32,80,101,116,114,111,108,101,117,109,32,69,120,116,114,97,99,116,105,111,110,194,160
Thanks
Using UNISTR did the trick for me. It removed the characters 160 and 194
update mytab set mycol = REPLACE(mycol,unistr('\00A0'),'')
trim() should work as expected! Sure it is a varchar2 column not a char column?
update hr.countries t
set t.country_name = t.country_name || ' ';
update hr.countries t
set t.country_name = trim(t.country_name);
Change the column type from char to varchar2, char column blank-pads the value with spaces to fill up the size of the field. So for a char(10) column, when you insert 'abc', it will automatically be inserted as 'abc '
in my database I have this char �. I want to locate them with a query
Select *
from Sometable
where somecolumn like '%�%'
this gets me no result.
I think it is ANSI encoding
use N like below
where col like N'%�%'
why do you think ,you need N prefix:
Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
Thanks to Martin Smith,Earlier i tested only with one character earlier and it worked,but as Martin pointed out, it returns all characters..
Below query works and returns only intended
select * from #demo where id like N'%�%'
COLLATE Latin1_General_100_BIN
Demo:
create table #demo
(
id nvarchar(max)
)
insert into #demo
values
(N'ﬗ'),
( N'�')
to know more about unicode,please see below links
http://kunststube.net/encoding/
https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/
This is the Unicode replacement character symbol.
It could match any of 2,048 invalid code points in the UCS-2 encoding (or the single character U+FFFD for the symbol itself).
You can use a range and a binary collate clause to match them all (demo).
WITH T(N)
AS
(
SELECT TOP 65536 NCHAR(ROW_NUMBER() OVER (ORDER BY ##SPID))
FROM master..spt_values v1,
master..spt_values v2
)
SELECT N
FROM T
WHERE N LIKE '%[' + NCHAR(65533) + NCHAR(55296) + '-' + NCHAR(57343) + ']%' COLLATE Latin1_General_100_BIN
You can use ASCII to find out the ascii code for that char
Select ascii('�')
And use CHAR to retrieve the char from that code and combine it in a LIKE expression
Select * from Sometable
where somecolumn like '%'+CHAR(63)+'%'
Note the collation you use can affect the result. Also it depends on the encoding used by your application to feed your data (UTF-8, UNICODE, etc). also how you store it VARCHAR, or NVARCHAR has a last say on what you see.
There's more here in this similar question
EDIT
#Mark
try this simple test:
create table sometable(somecolumn nvarchar(100) not null)
GO
insert into sometable
values
('12345')
,('123�45')
,('12345')
GO
select * from sometable
where somecolumn like '%'+CHAR(63)+'%'
GO
This only means that character was stored win the as a "?" in this test.
When you see a � it means the app where you are seeing isn't quite sure what to print out.
It also mean OP probably needs to find out what char is that using a query.
Also note it means a string outputted like ��� can be 3 formed by different characters.
CHAR(63) was just an example, but you are right this in the ASCII table will be a standard interrogation.
EDIT
#Bridge
Not with time right now to deep dig in it but the below test don't worked
Select ascii('�'), CHAR(ascii('�')), UNICODE(N'�'), CHAR(UNICODE(N'�'))
GO
create table sometable(somecolumn nvarchar(100) not null)
GO
insert into sometable
values
('12345')
,('123�45')
,('12345')
,('12'+NCHAR(UNICODE(N'�'))+'345')
GO
select * from sometable
where somecolumn like '%'+CHAR(63)+'%'
select * from sometable
where somecolumn like '%'+NCHAR(UNICODE(N'�'))+'%'
GO
I was learning how to use len() function. When I found out the length of a cell having 12 characters, it gave me result 12. Now I was thinking that arent the SQL strings null terminated(As if they would have been then len() should have returned 13 not 12)?
Please help me out.
Thanks
Well, first - the len function does not depend on null termination, programming languages not using null termination ALSO have a len function an it works.
Thus, a len function in SQL will give you the length of the string AS THE SERVER STORES IT - what do you care how that works?
Actually it will likely not be null terminated as this would make it hard to split a string over multiple database pages. And even if - this would be seriously implementation dependent (and you don't say which product you mean - the SQL language says nothing about how the server internally stores strings).
So, at the end your question is totally irrelevant. All that is relevant is that the len function implementation is compatible with the internal storage.
In SQL Server, LEN will ignore trailing spaces (http://msdn.microsoft.com/en-us/library/ms187403.aspx) - here's a modified example from that link:
PRINT 'Testing with ANSI_PADDING ON'
SET ANSI_PADDING ON ;
GO
CREATE TABLE t1
(
charcol CHAR(16) NULL
,varcharcol VARCHAR(16) NULL
,varbinarycol VARBINARY(8)
) ;
GO
INSERT INTO t1
VALUES ('No blanks', 'No blanks', 0x00ee) ;
INSERT INTO t1
VALUES ('Trailing blank ', 'Trailing blank ', 0x00ee00) ;
SELECT 'CHAR' = '>' + charcol + '<'
,'VARCHAR' = '>' + varcharcol + '<'
,varbinarycol
,LEN(charcol)
,LEN(varcharcol)
,DATALENGTH(charcol)
,DATALENGTH(varcharcol)
FROM t1 ;
GO
PRINT 'Testing with ANSI_PADDING OFF' ;
SET ANSI_PADDING OFF ;
GO
CREATE TABLE t2
(
charcol CHAR(16) NULL
,varcharcol VARCHAR(16) NULL
,varbinarycol VARBINARY(8)
) ;
GO
INSERT INTO t2
VALUES ('No blanks', 'No blanks', 0x00ee) ;
INSERT INTO t2
VALUES ('Trailing blank ', 'Trailing blank ', 0x00ee00) ;
SELECT 'CHAR' = '>' + charcol + '<'
,'VARCHAR' = '>' + varcharcol + '<'
,varbinarycol
,LEN(charcol)
,LEN(varcharcol)
,DATALENGTH(charcol)
,DATALENGTH(varcharcol)
FROM t2 ;
GO
DROP TABLE t1
DROP TABLE t2
If we're talking pure SQL, there's no NUL terminator for you to worry about. If we're talking interfacing to SQL from other languages (e.g. C), then the answer depends on the language in question.
There are a couple of relevant points worth remembering:
There are two character types in SQL: CHAR(N) and VARCHAR(N). The former is always the same length (N) and padded with spaces; the latter is variable-length (up to N chars).
In Transact-SQL, LEN returns the length on the string excluding trailing spaces.
In some SQL strings are zero- terminated.
On some SQL they have a leading length byte/ word.
This of course does not matter for the len() function.
But it does matter if you want to insert a \0 into the string.
Usually varchar has a leading length byte.
But char is \0 terminated.
I have a table, my_table, that has a field my_field. myfield is defined as VARCHAR(7). When I do:
SELECT myfield
FROM my_table;
I get what appears to be the entire 7 characters, but I only want the actual data.
I tried:
SELECT TRIM(myfield)
FROM my_table;
and several variations. But instead of getting 'abcd', I get 'abcd '.
How do I get rid of the trailing blanks?
As others have said:
trim whitespace before data enters the database ("Mop the floor...);
ensure this is not actually a column of type CHAR(7).
Additionally, add a CHECK constraint to ensure no trailing spaces ("...fix the leak.") While you are at it, also prevent leading spaces, double spaces and zero-length string e.g.
CREATE TABLE my_table
(
myfield VARCHAR(7) NOT NULL
CONSTRAINT myfield__whitespace
CHECK (
NOT (
myfield = ''
OR myfield LIKE ' %'
OR myfield LIKE '% '
OR myfield LIKE '% %'
)
)
);-
VARCHAR columns will not pad the string you insert, meaning if you are getting 'ABCD ', that's what you stored in the database. Trim your data before inserting it.
Make sure you are not using the CHAR datatype, which will pad your data in the way you suggest. In any case:
SELECT TRIM(myfield) FROM mytable;
will work.
Make sure also that you are not confusing the way the SQL interpreter adds padding chars to format the data as a table with the actual response.
Make sure that you are not inserting data in this column from a CHAR(7) field.
You need to trim your result when selecting as opposed to when inserting, eg:
SELECT TRIM(myfield) FROM my_table;