7
Answers

Help with while loop in sql server

Schleid Alex

Schleid Alex

4y
709
1
I have this query
 
Declare @Fnum nchar(5)
 
While (len(@Fnum)<5
Begin
 Set @Fnum += '0
End
 Print @Fnum
 
I am expecting 0000 as result
 
 But this is not happening, I only have 0 as result?
 
Can I have some help please?
 
Answers (7)
3
Varun Setia

Varun Setia

158 12.1k 771.4k 4y
For generating repeated characters one function named REPLICATE is available in SQL Server , below is the code
 
  1. Declare @Fnum nvarchar(5)   
  2. SET @Fnum= REPLICATE('0',5)  
  3. PRINT @Fnum  
 
3
Pankaj Patel

Pankaj Patel

69 27k 2.3m 4y
Hi Schleid Alex,
 
You can do your mentioned scenarion in following 3 ways:
 
(1) declare @Fnum nvarchar(5)=''
  • Set '' at declaration time.
(2) while (len(isnull(@Fnum, '')) < 5)
  • check null at length check time.
  • First approach is better than this one.
(3) select right('00000' + cast(isnull(@Fnum, '') as nvarchar(5)), 5)
  • You can do padding by this way instead of while loop.
  • This approach is better than above both way.
Note
  • For all above approaches you must have to use nvarchar instead of nchar
Hope, this will help you!
3
Sachin Singh

Sachin Singh

11 55.8k 87.6k 4y
  1. Declare @Fnum nvarchar(5)=''  
  2. While (len(@Fnum)<5)  
  3.   
  4.     Begin  
  5.      set @Fnum += '0'  
  6.          
  7.     End  
  8.   
  9.  select @Fnum  
  10.   
2
Varun Setia

Varun Setia

158 12.1k 771.4k 4y
 Problem is with nchar make it and cast it to nvarchar, also intialize it, otherwise it will be null.
Also, you are working with string so use CONCAT  
  1. Declare @Fnum nvarchar(5)=''  
  2.    
  3. While (len(@Fnum))<5  
  4. Begin  
  5.  SET @Fnum=CAST(CONCAT(@Fnum,'0'AS nvarchar(5))  
  6.  --PRINT @Fnum  
  7. End  
  8.  PRINT @Fnum  
 
 
 
 
1
Mageshwaran R

Mageshwaran R

NA 10.8k 1.1m 4y
Hi Alex,
 
Try this query:
 
  1. DECLARE @Fnum nvarchar(5)  
  2. SET @Fnum=1  
  3. WHILE ( @Fnum < 5)  
  4. BEGIN  
  5.     PRINT 'The Fnum value is = ' + CONVERT(VARCHAR,@Fnum)  
  6.     SET @Fnum  = @Fnum  + 1  
  7. END  
 
0
Mageshwaran R

Mageshwaran R

NA 10.8k 1.1m 4y
Try this:
 
  1. DECLARE @Fnum nvarchar(5)  
  2. SET @Fnum=''  
  3. WHILE ( @Fnum < 5)  
  4. BEGIN  
  5.    if(@Fnum='')  
  6.    begin  
  7.   SET @Fnum='0000'  
  8.     PRINT 'The Fnum value is = ' + CONVERT(VARCHAR,@Fnum)  
  9.     end  
  10.     else  
  11.     begin  
  12.     SET @Fnum  =  CAST(LEFT('0000', LEN('0000')-LEN(CAST(@Fnum+1 AS NVARCHAR(5)))) +  CAST(@Fnum+1 AS NVARCHAR(5)) AS NVARCHAR(5))  
  13.      PRINT 'The Fnum value is = ' + CONVERT(VARCHAR,@Fnum)  
  14.     end  
  15. END  
 
0
Kamil Krupski

Kamil Krupski

NA 238 17 4y
declare @Fnum as nvarchar() and set default value empty.
 
Declare @Fnum nvarchar(5) = ''