October 15, 2009 at 1:14 pm
Ok, so if you want to keep your sanity, it probably would be best not to ask why I need to do this :-); however, this is my question. Is there a way for sql to automatically enter blank spaces into a field. I have a field that is a varchar(9). What I need is if you enter say '123' in that field, add enough blank spaces to the front of it, to take all 9 spaces, so in this case, 6 spaces; however, if you put '1234' then it would only add 5 spaces. Is this possible?
Thanks,
Jordon
October 15, 2009 at 1:24 pm
The only thing I can think of is using a trigger to update that field after insert
update query:
--drop table #t
create table #t (spaces nvarchar(9))
insert into #t
select 'me' union all
select 'you' union all
select 'allofus' union all
select 'they'
update #t
set spaces = right(' '+spaces, 9) from #t
select * from #t
October 15, 2009 at 2:32 pm
Jordan, you are thinking procedurally here too.
SQL stores values. Don't worry about formatting until you DISPLAY those values.
Check this out:
declare @sample int
set @sample = 123
select @sample
select str(@sample)
The STR() function right adjusts, and can decimal-align a numeric value. But we store it simply as an integer for efficiency's sake. Jeff Moden would tell you to not even bother with the STR() function. Just pass the value back to the calling application and let IT handle the formatting.
Some people will tell you I'm already crazy. So, yes, I am asking you why you think you need to store a left padded number in a varchar(10). Why waste time, space, and effort tossing in useless blanks?
__________________________________________________
Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills
October 17, 2009 at 7:11 pm
Agreed on all counts, Bob.
--Jeff Moden
Change is inevitable... Change for the better is not.
October 18, 2009 at 8:17 am
If you need to ignore the suggestions of Bob Hovious and Jeff Moden look at this code and decide what you want to do.
CREATE TABLE #Demo(Col1 VARCHAR(9),Col2 VARCHAR(9))
DECLARE @Blanks VARCHAR(9)
DECLARE @Value VARCHAR(9)
SET @Value = '123'
SET @Blanks = ' '
INSERT INTO #Demo
VALUES (RIGHT(@Blanks + @Value,9),@Value)
SELECT Col1 AS 'this is what I want',LEN(Col1) AS 'Lenght to prove what I want has leading blanks',RIGHT(' ' + Col2,9) AS 'Space saving'
,LEN(RIGHT(' ' + Col2,9))AS 'Prove space savings has leading blanks',Col2 AS 'Recommended by Bob Hovious'
FROM #Demo
DROP TABLE #Demo
October 18, 2009 at 9:32 am
Heh... the only reason why I didn't post any code to do the job was because mcha7628 and Bob both did. The STR() function is the easiest... the RIGHT(someblanks+varchardata,len) is the fastest but both are effective and fast.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply