Why does ExecuteReader() pad strings with traling spaces?
Asked Answered
C

1

2

I have two queries:

Q1: select name from presidents where country = 'USA'
Q2: select 'Obama' as name from presidents where country = 'USA'

When using System.Data.Odbc.OdbcCommandExecuteReader then the returned DbDataReader contains 'Obama' in case of Q1 and 'Obama ' in case of Q2.

Why is the string padded with trailing spaces in case of Q2 and what is the remedy?

Trimming is ugly and even wrong in some cases. I am using .Net Framework 3.5.

Here is the test code

OdbcCommand cmd = new OdbcCommand();
cmd.Connection = (OdbcConnection)DatabaseContext.Connection;
cmd.CommandText = "select 'Obama' from dual";
cmd.CommandType = CommandType.Text;
OdbcDataReader r = cmd.ExecuteReader();
if (r.Read())
{
    String s = r.GetString(0);
    // s now contains "Obama          "
    // with trailing spaces
}
Catron answered 5/3, 2014 at 10:7 Comment(0)
D
4

ExecuteReader returns data from the underlying data source without doing any padding.

It's your underlying data source, in this case Oracle, that is returning trailing spaces.

Google for "oracle trailing spaces" to understand why this is, and in particular to understand the difference between CHAR and VARCHAR data types in Oracle.

Meanwhile, you can either remove the trailing spaces in the SQL query:

SELECT RTRIM(Col1) FROM ...

Or remove them in the client:

string s = r.GetString(0).TrimEnd()
Dedicated answered 5/3, 2014 at 12:51 Comment(1)
Indeed select 'x' from dual is not the same as select trim('x') from dualCatron

© 2022 - 2024 — McMap. All rights reserved.