0

I have a consult in sql where i select many fields, but I need that some fields have specific length, If the value of the field does not have the specified length, it must be filled with zeros or spaces

I filled this values in the server c# with a while for each one, but i need a best solution

The next table is a part of the records in database:

id  code

10  5987
11  34567
12  242
13  43244

And I paste a part of the code of server code

id=reader["id"]== DBNull.Value?string.Empty:Convert.ToString(reader["id"]);
                        while ( id.Length<15)
                        {
                            id= " " +id;
                        }
code =reader["code"]== DBNull.Value?string.Empty:Convert.ToString(reader["code"]);
                        while ( code.Length<10)
                        {
                            code = "0" +code;
                        }

I hope you can help me, thanks

crista
  • 47
  • 1
  • 1
  • 9
  • Please add the SELECT query you are executing so we can help you – Camilo Terevinto Apr 21 '18 at 02:07
  • 2
    Possible duplicate of [Pad a string with leading zeros so it's 3 characters long in SQL Server 2008](https://stackoverflow.com/questions/16760900/pad-a-string-with-leading-zeros-so-its-3-characters-long-in-sql-server-2008) – Camilo Terevinto Apr 21 '18 at 02:08
  • Instead of your while loop use PadLeft, i.e. `id = id.PadLeft(15, ' ')` and `code = code.PadLeft(10, '0')` – ckuri Apr 21 '18 at 06:37

0 Answers0