How can I conserve the initial zero when convert numeric to string using STR()

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • angellian@gmail.com

    How can I conserve the initial zero when convert numeric to string using STR()

    Sorry to raise a stupid question but I tried many methods which did
    work.
    how can I conserve the initial zero when I try to convert STR(06) into
    string in SQL statment?
    It always gives me 6 instead of 06.

    Thanks a lot.

  • Mike C#

    #2
    Re: How can I conserve the initial zero when convert numeric to string using STR()

    You can't "preserve" the zero. Integer 06 = Integer 6 = Integer
    00000000006.

    If you want to convert an integer to a varchar you can prepend a 0 character
    to the result:

    SELECT '0' + CAST(06 AS VARCHAR)

    Returns '06'. The downside to this method is that if you do something like

    SELECT '0' + CAST(10 AS VARCHAR)

    You'll end up with '010' which may or may not be what you want. You can
    build on this example with the SUBSTRING function to get exactly what you
    really want out of it.

    <angellian@gmai l.com> wrote in message
    news:1148779910 .070643.296910@ g10g2000cwb.goo glegroups.com.. .[color=blue]
    > Sorry to raise a stupid question but I tried many methods which did
    > work.
    > how can I conserve the initial zero when I try to convert STR(06) into
    > string in SQL statment?
    > It always gives me 6 instead of 06.
    >
    > Thanks a lot.
    >[/color]


    Comment

    • --CELKO--

      #3
      Re: How can I conserve the initial zero when convert numeric to string using STR()

      You are confusing the PHYSICAL display with the internal LOGICAL model.


      This is SQL and not COBOL. There is no initial zero in a number; there
      is an internal binary, BCD or whatever the hard uses representation.

      Your next problem is that you do not understand that dispaly is NEVER
      done in the database, but in the front end application. That is the
      most basic concept of *any* tiered architecture, not just SQL.

      Comment

      • Erland Sommarskog

        #4
        Re: How can I conserve the initial zero when convert numeric to string using STR()

        --CELKO-- (jcelko212@eart hlink.net) writes:[color=blue]
        > Your next problem is that you do not understand that dispaly is NEVER
        > done in the database, but in the front end application. That is the
        > most basic concept of *any* tiered architecture, not just SQL.[/color]

        Working so long as you have done in the database trade should have learnt
        you to never say never.

        There is at least one obvious case where formatting of output must be
        done in SQL: to wit when the display is done in a standard query tool
        like Query Analyzer. Which typically is the case for admin stuff.


        --
        Erland Sommarskog, SQL Server MVP, esquel@sommarsk og.se

        Books Online for SQL Server 2005 at

        Books Online for SQL Server 2000 at

        Comment

        • Tony Rogerson

          #5
          Re: How can I conserve the initial zero when convert numeric to string using STR()

          > This is SQL and not COBOL. There is no initial zero in a number; there[color=blue]
          > is an internal binary, BCD or whatever the hard uses representation.[/color]

          This is SQL SERVER not SQL and not COBOL, SQL SERVER has many facilities to
          aid the developer in creating a highly scalable, robust and maintainable
          architecture.

          Standard SQL is very weak in terms of features that we need out in the real
          world.
          [color=blue]
          > Your next problem is that you do not understand that dispaly is NEVER
          > done in the database, but in the front end application. That is the
          > most basic concept of *any* tiered architecture, not just SQL.[/color]

          "Display" can never be done in the database because the database is a
          service and has such has no UI, we use tools to get at the data.

          The big problem here is your continued misconception that ALL formatting
          should be done in the front end application, have you actually sat down and
          thought about what that means? The fundemental principle of tiered
          architecture design and development is that formatting is done where it is
          most sensible and efficient, in terms of development and support cost and in
          terms of performance.

          My blog entry on this covers in more detail:


          I see you use CTE, why don't you pull the results down into the application,
          CTE's are a form of formatting for display purposes, as is COALESCE on the
          SELECT clause, as is ORDER BY etc... Just where do you draw the line?

          Anyway, you are still stuck in the mainframe model of all resources are in
          the same box and that you use the VTAM protocol out to remote terminals.

          --
          Tony Rogerson
          SQL Server MVP
          http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
          Server Consultant
          http://sqlserverfaq.com - free video tutorials


          "--CELKO--" <jcelko212@eart hlink.net> wrote in message
          news:1148830663 .994422.182500@ y43g2000cwc.goo glegroups.com.. .[color=blue]
          > You are confusing the PHYSICAL display with the internal LOGICAL model.
          >
          >
          > This is SQL and not COBOL. There is no initial zero in a number; there
          > is an internal binary, BCD or whatever the hard uses representation.
          >
          > Your next problem is that you do not understand that dispaly is NEVER
          > done in the database, but in the front end application. That is the
          > most basic concept of *any* tiered architecture, not just SQL.
          >[/color]


          Comment

          • Cimode

            #6
            Re: How can I conserve the initial zero when convert numeric to string using STR()

            Something like this may help...Assuming your column name is COLUMN1 and
            COLUMN1 has a numeric type.

            select case
            when COLUMN1 < 10 then '0' + cast(COLUMN1 as varchar(10))
            end
            when COLUMN1 > = 10 then cast(COLUMN1 as varchar(10)) end
            .......(rest of your statement...)

            Hope this helps...

            Comment

            • Tony Rogerson

              #7
              Re: How can I conserve the initial zero when convert numeric to string using STR()

              Hi Angellian,

              For 2 character string you can just use CASE...

              declare @number tinyint
              set @number = 2

              select case when @number between 0 and 9 then '0' else '' end + cast(
              @number as varchar(2) )

              Otherwise, if your resultant string needs to be bigger than 2 characters do
              this...

              declare @number int
              declare @string varchar(10)
              declare @size_of_fixed_ string tinyint
              set @size_of_fixed_ string = 10
              set @number = 40

              print replicate( '0', @size_of_fixed_ string )

              set @string = left( replicate( '0', @size_of_fixed_ string ),
              @size_of_fixed_ string - len( @number ) ) + cast( @number as varchar(10) )

              print @string



              --
              Tony Rogerson
              SQL Server MVP
              http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
              Server Consultant
              http://sqlserverfaq.com - free video tutorials


              <angellian@gmai l.com> wrote in message
              news:1148779910 .070643.296910@ g10g2000cwb.goo glegroups.com.. .[color=blue]
              > Sorry to raise a stupid question but I tried many methods which did
              > work.
              > how can I conserve the initial zero when I try to convert STR(06) into
              > string in SQL statment?
              > It always gives me 6 instead of 06.
              >
              > Thanks a lot.
              >[/color]


              Comment

              • --CELKO--

                #8
                Re: How can I conserve the initial zero when convert numeric to string using STR()

                >> There is at least one obvious case where formatting of output must be done in SQL: to wit when the display is done in a standard query tool like Query Analyzer. <<

                No, that formatting is done in the Query Analyzer, which is a program
                and not part of SQL. Trust me, we never voted on a "standard query
                tool" in ANSI X3H2.

                Comment

                • --CELKO--

                  #9
                  Re: How can I conserve the initial zero when convert numeric to string using STR()

                  >> I see you use CTE, why don't you pull the results down into the application, CTE's are a form of formatting for display purposes, as is COALESCE on the SELECT clause, as is ORDER BY etc... Just where do you draw the line? <<

                  UNH? CTEs are virtual tables and have nothing to do with display. Do
                  ypou also think that VIEWs and derived tables are formatting for user
                  display? COALESCE is a function that works with NULLs and CAST() to
                  get another internal data type result.

                  Things like CONVERT() on dates or PRINT in T-SQL is formatting.

                  Comment

                  • Stu

                    #10
                    Re: How can I conserve the initial zero when convert numeric to string using STR()

                    Just cause I've seen a couple of examples using CASE; I use trick
                    similar to your second example:

                    SELECT RIGHT('0' +CONVERT(varcha r(2), @number), 2)

                    Granted, it only works on a two-digit number, but it saves typing. The
                    REPLICATE idea is pretty smooth, though.

                    Stu

                    Tony Rogerson wrote:[color=blue]
                    > Hi Angellian,
                    >
                    > For 2 character string you can just use CASE...
                    >
                    > declare @number tinyint
                    > set @number = 2
                    >
                    > select case when @number between 0 and 9 then '0' else '' end + cast(
                    > @number as varchar(2) )
                    >
                    > Otherwise, if your resultant string needs to be bigger than 2 characters do
                    > this...
                    >
                    > declare @number int
                    > declare @string varchar(10)
                    > declare @size_of_fixed_ string tinyint
                    > set @size_of_fixed_ string = 10
                    > set @number = 40
                    >
                    > print replicate( '0', @size_of_fixed_ string )
                    >
                    > set @string = left( replicate( '0', @size_of_fixed_ string ),
                    > @size_of_fixed_ string - len( @number ) ) + cast( @number as varchar(10) )
                    >
                    > print @string
                    >
                    > http://sqlblogcasts.com/blogs/tonyro...05/29/765.aspx
                    >
                    > --
                    > Tony Rogerson
                    > SQL Server MVP
                    > http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
                    > Server Consultant
                    > http://sqlserverfaq.com - free video tutorials
                    >
                    >
                    > <angellian@gmai l.com> wrote in message
                    > news:1148779910 .070643.296910@ g10g2000cwb.goo glegroups.com.. .[color=green]
                    > > Sorry to raise a stupid question but I tried many methods which did
                    > > work.
                    > > how can I conserve the initial zero when I try to convert STR(06) into
                    > > string in SQL statment?
                    > > It always gives me 6 instead of 06.
                    > >
                    > > Thanks a lot.
                    > >[/color][/color]

                    Comment

                    • Damien

                      #11
                      Re: How can I conserve the initial zero when convert numeric to string using STR()

                      --CELKO-- wrote:[color=blue][color=green][color=darkred]
                      > >> I see you use CTE, why don't you pull the results down into the application, CTE's are a form of formatting for display purposes, as is COALESCE on the SELECT clause, as is ORDER BY etc... Just where do you draw the line? <<[/color][/color]
                      >
                      > UNH? CTEs are virtual tables and have nothing to do with display. Do
                      > ypou also think that VIEWs and derived tables are formatting for user
                      > display? COALESCE is a function that works with NULLs and CAST() to
                      > get another internal data type result.
                      >
                      > Things like CONVERT() on dates or PRINT in T-SQL is formatting.[/color]

                      Hi Joe,

                      I didn't understand Tony's point about CTEs, but I think his point
                      about COALESCE stands. Surely, COALESCE is shorthand for having
                      formatting code at the front end like:

                      If Column1 is not null then
                      show Column1
                      Else if column2 is not null then
                      show Column2
                      Else if column3 is not null then
                      :
                      :
                      :
                      Else
                      show ColumnN
                      End If

                      Damien

                      Comment

                      • Tony Rogerson

                        #12
                        Re: How can I conserve the initial zero when convert numeric to string using STR()

                        > UNH? CTEs are virtual tables and have nothing to do with display. Do[color=blue]
                        > ypou also think that VIEWs and derived tables are formatting for user
                        > display? COALESCE is a function that works with NULLs and CAST() to
                        > get another internal data type result.
                        >
                        > Things like CONVERT() on dates or PRINT in T-SQL is formatting.[/color]

                        Ok - I conceede CTEs, I was thinking about them within the scope of paging
                        on which you have in the past stated you would have the front end perform,
                        that literally means pushing a million rows over the network to the front
                        end.
                        [color=blue]
                        > Things like CONVERT() on dates or PRINT in T-SQL is formatting.[/color]

                        The operator was trying to create a string with leading zeros which you
                        stated should be done in the front end.

                        Why on earth would you want to go to all the effort of using a 3GL / 4GL to
                        format the data when you can just simply do it in TSQL within the SQL Server
                        itself - nice and simple, nice and easy to support and maintain.

                        Your method relies on additional skills, the developer would need to
                        understand a programming language as well as SQL, that then translates into
                        a support and maintanence burden which costs money.

                        You can very easily do the formatting in the TSQL and use Integration
                        Services or DTS to export the data out to whatever you want - XML, XLS
                        etc...

                        Your recommendations around formatting date back to the 70's where rdbms
                        didn't have many facilities available for the developer other than SUM,
                        COUNT, MIN, MAX and AVG.

                        --
                        Tony Rogerson
                        SQL Server MVP
                        http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
                        Server Consultant
                        http://sqlserverfaq.com - free video tutorials


                        "--CELKO--" <jcelko212@eart hlink.net> wrote in message
                        news:1149114884 .873451.172270@ g10g2000cwb.goo glegroups.com.. .[color=blue][color=green][color=darkred]
                        >>> I see you use CTE, why don't you pull the results down into the
                        >>> application, CTE's are a form of formatting for display purposes, as is
                        >>> COALESCE on the SELECT clause, as is ORDER BY etc... Just where do you
                        >>> draw the line? <<[/color][/color]
                        >
                        > UNH? CTEs are virtual tables and have nothing to do with display. Do
                        > ypou also think that VIEWs and derived tables are formatting for user
                        > display? COALESCE is a function that works with NULLs and CAST() to
                        > get another internal data type result.
                        >
                        > Things like CONVERT() on dates or PRINT in T-SQL is formatting.
                        >[/color]


                        Comment

                        • Anith Sen

                          #13
                          Re: How can I conserve the initial zero when convert numeric to string using STR()

                          >> Why on earth would you want to go to all the effort of using a 3GL / 4GL[color=blue][color=green]
                          >> to format the data when you can just simply do it in TSQL within the SQL
                          >> Server itself - nice and simple, nice and easy to support and maintain.[/color][/color]

                          The general answer is that one would prefer to have the centralized database
                          as generic as possible so that it can support a variety of applications.

                          Having an application specific formatting at the central data source tend to
                          generate something called "applicatio n bias". Considering the OP's question,
                          given certain 5 applications requesting same data formatted in 5 different
                          ways, should he formulate a single generic query and do the formatting in
                          the application or should he create 5 different queries to support each
                          application? How about when the number of applications increases to 50? Or
                          say 500?

                          While it may appear to be efficient and easy to manage in the short term, it
                          can often be highly detrimental to the long term stability and management of
                          data centric systems.

                          This is nothing new but such bias is known to software engineers for decades
                          now. For details on why this separation of concern is important for data
                          oriented systems, ~Principles of Program Design~ by Michael Jackson is a
                          good book.

                          --
                          Anith


                          Comment

                          • Erland Sommarskog

                            #14
                            Re: How can I conserve the initial zero when convert numeric to string using STR()

                            --CELKO-- (jcelko212@eart hlink.net) writes:[color=blue][color=green][color=darkred]
                            >>> There is at least one obvious case where formatting of output must be[/color][/color][/color]
                            done in SQL: to wit when the display is done in a standard query tool like
                            Query Analyzer. <<[color=blue]
                            >
                            > No, that formatting is done in the Query Analyzer,[/color]

                            QA only has a standard formatting, with no options to specify a how a
                            certainly column should look like.

                            Thus, if you want a certain format when you look at the data in QA, SQL
                            is the only place to do formatting.
                            [color=blue]
                            > which is a program and not part of SQL. Trust me, we never voted on a
                            > "standard query tool" in ANSI X3H2.[/color]

                            I never said so. I only meant to say that it is a plain query tool,
                            and about every RDBMS comes with one.


                            --
                            Erland Sommarskog, SQL Server MVP, esquel@sommarsk og.se

                            Books Online for SQL Server 2005 at

                            Books Online for SQL Server 2000 at

                            Comment

                            • Erland Sommarskog

                              #15
                              Re: How can I conserve the initial zero when convert numeric to string using STR()

                              Anith Sen (anith@bizdatas olutions.com) writes:[color=blue]
                              > The general answer is that one would prefer to have the centralized
                              > database as generic as possible so that it can support a variety of
                              > applications.[/color]

                              I think the Perl has the right answer to this: There is more than one
                              way do it!

                              That is, if you can do things either in the server or the in the client/
                              middile layer, you can pick what fits best for the situation.


                              --
                              Erland Sommarskog, SQL Server MVP, esquel@sommarsk og.se

                              Books Online for SQL Server 2005 at

                              Books Online for SQL Server 2000 at

                              Comment

                              Working...