Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

sql - Remove blank-padding from to_char() output

I generate a view from this:

create or replace view datetoday as
select to_char(dt, 'yyyy-mm-dd') as date, to_char(dt, 'Day') as weekday from 
(select ('2013-03-01'::date + i) dt from generate_series(0,'2013-03-03'::date - 2013-03-01'::date) 
as t(i)) as t;

It gives me the weekday info as text type. Then I use:

select date::date, weekday::varchar from datetoday;

Now the table is like

2013-3-1 Friday
2013-3-2 Saturday

If I want to choose the entry:

select * from datetoday where weekday='Friday'

to change it from text to character varying.

It seems that the length is fixed is not according to each word length.
For example 'Friday' should have length 6 and Wednesday length 9.
How can I change this, let the length be the actual length of the word?

Because later I will compare this table's weekday column to another table's weekday column. Like

where a.weekday=b.weekday

The other weekday is from user from jsp, so the length varies.
Now the length is fixed, the comparison fails.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The pattern 'Day' is blank-padded to the right, making all days 9 characters long. Use the FM Template Pattern Modifier to remove any padding:

SELECT d::date AS day
     , to_char(d, 'yyyy-mm-dd') AS day_text
     , to_char(d, 'FMDay')      AS weekday
FROM generate_series('2013-03-01'::date
                   , '2013-03-07'::date
                   , interval '1 day') d;

Also demonstrating generate_series() for timestamps. One less query level.
If you need an actual date in the view, make it an actual type date, don't convert to text and back.
And don't use the basic type name date as column name. Using day instead.
And I would just use text for the text. No point in converting to varchar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...