| Author |
Topic  |
|
|
mmkrishna1919
Yak Posting Veteran
India
54 Posts |
Posted - 01/08/2013 : 06:36:54
|
Hi All,
my requirement is need to form a fixed length string by concatenating three columns. Out of 3 fields if last_name field is null then i need to replace with 20 spaces.
I tried with below statement:
select @data_var= column1+ isnull(lastname,replicate(' ',20)) + column3
the output of this above statement is: data of column1+one space+data of column2
"it is returning one space but i am expecting 20 spaces"
If i slightly modify the above statement as below with case statement i am getting correct results:
select @data_var= column1+ cast(isnull(lastname,replicate(' ',20)) as char(20)) + column3
the output of this above statement is: data of column1+20 spaces+data of column2
If i have this piece of code(mentioned above) in a block of code,then i am getting above mentioned issue.
If i execute this as a single block even without case atatement i am getting expected results(20 spaces).
declare @targ char(300), @col1 char(20), @col2 char(3) set @col2='hai' set @col1=null select @targ=@col2+isnull(@col1,replicate(' ',20))+@col2 select @targ
Both col1 and clo2 are char data type only..
Please suggest what is happening in first statement(without case) and second(with case)?
Thanks,
M.MURALI kRISHNA |
|
|
nigelrivett
Flowing Fount of Yak Knowledge
United Kingdom
3328 Posts |
Posted - 01/08/2013 : 07:05:58
|
Maybe there is a single space in lastname?
========================================== Cursors are useful if you don't know sql. SSIS can be used in a similar way. Beer is not cold and it isn't fizzy. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
India
47023 Posts |
Posted - 01/08/2013 : 23:38:19
|
what was dataype of lastname?
------------------------------------------------------------------------------------------------------ SQL Server MVP http://visakhm.blogspot.com/
|
 |
|
|
shan007
Starting Member
USA
8 Posts |
Posted - 01/09/2013 : 04:09:28
|
This is due to length of the 'lastname' column referred in your first script, seems it's length is 1. That's why isnull replaces only one space. ISNULL would replace value based on the type\length of the expression you want to replace with.
In your second script you use Cast as char(20), here cast function extends the length(20) no matter what was declared length of column, that's why it adds 20 spaces.
If you look at your last script, 'col1' length set as 20, that's why you get 20 spaces without Cast function. Hope you get it.
I'm here to learn new things everyday.. |
 |
|
|
mmkrishna1919
Yak Posting Veteran
India
54 Posts |
Posted - 01/09/2013 : 05:44:18
|
Thanks alot shan007 for resolution.
M.MURALI kRISHNA |
 |
|
| |
Topic  |
|