0

I have an int column that I need to convert it into text. I tried to convert it into varchar but it did not display the preceding 0 when I tried to run the report thru batch file or export it to Excel,.

SELECT 
    CAST(a.Value AS VARCHAR(20)) AS Value
FROM 
    dbo.HPatientIdentifiers a
JOIN 
    HPatientVisit b ON a.Patient_oid = b.Patient_oid
WHERE 
    b.VisitTypeCode IN ('IP', 'EOP')
    AND a.IsVersioned = 0
    AND a.TYpe = 'MR'
    AND b.VisitEndDateTime >= DATEADD(dd, -1, GETDATE())
ORDER BY  
     a.Value

OUTPUT:

Value
------
4824
5663
10276
10459

Expected result:

Value
-------
004824
005663
010276
010459

Please help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Lina
  • 1
  • 1

1 Answers1

1

using right() and concatenating 0s to the casted varchar() column:

SELECT right('000000'+CAST(a.Value as varchar(20)),6) AS Value

FROM dbo.HPatientIdentifiers a
JOIN HPatientVisit b
ON a.Patient_oid=b.Patient_oid

WHERE b.VisitTypeCode IN ('IP','EOP')
AND a.IsVersioned=0
AND a.TYpe='MR'
AND b.VisitEndDateTime >= DATEADD(dd,-1, GETDATE())

ORDER BY  a.Value
SqlZim
  • 37,248
  • 6
  • 41
  • 59