function to receive a character input and return date format (with incorrect input)stored procedure returns ERROR 1305 (42000): FUNCTION does not existHelp with tricky update statementIn PostgreSQL, is there a type-safe first() aggregate function?How do I create a user-defined aggregate function in MySQL (redux)?Conversion of a varchar data type to a datetime data type resulted in an out-of-range valuehow to convert this varchar to datetime format?Excel Import ID, Data Type DoubleQuery Time is doubled because of a column in selectDatetime to formatted Date Implicit Conversioncreating postgresql function with table as input

If a warlock with the Repelling Blast invocation casts Eldritch Blast and hits, must the targets always be pushed back?

What is the strongest case that can be made in favour of the UK regaining some control over fishing policy after Brexit?

How to back up a running remote server?

How to pronounce 'C++' in Spanish

Why isn't the definition of absolute value applied when squaring a radical containing a variable?

Providence Pentominoes Puzzle By Andrew Bradburn (Jigsaw)

Was there a Viking Exchange as well as a Columbian one?

Pulling the rope with one hand is as heavy as with two hands?

Binary Numbers Magic Trick

Is there really no use for MD5 anymore?

Does this extra sentence in the description of the warlock's Eyes of the Rune Keeper eldritch invocation appear in any official reference?

function to receive a character input and return date format (with incorrect input)

Why the difference in metal between 銀行 and お金?

How to stop co-workers from teasing me because I know Russian?

US visa is under administrative processing, I need the passport back ASAP

A possible fake AI on Patreon!

How can governments justify taking income tax on earnings, and then taking more tax on spending?

How do Bards prepare spells?

How to figure out whether the data is sample data or population data apart from the client's information?

What is the difference between `command a[bc]d` and `command `ab,cd`

Examples of non trivial equivalence relations , I mean equivalence relations without the expression " same ... as" in their definition?

Any examples of headwear for races with animal ears?

Hilbert Space and Banach Space

How could Tony Stark make this in Endgame?



function to receive a character input and return date format (with incorrect input)


stored procedure returns ERROR 1305 (42000): FUNCTION does not existHelp with tricky update statementIn PostgreSQL, is there a type-safe first() aggregate function?How do I create a user-defined aggregate function in MySQL (redux)?Conversion of a varchar data type to a datetime data type resulted in an out-of-range valuehow to convert this varchar to datetime format?Excel Import ID, Data Type DoubleQuery Time is doubled because of a column in selectDatetime to formatted Date Implicit Conversioncreating postgresql function with table as input






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















Hope you're doing well



I need to write a function to receive a string character and return the date format . For example the input is 20120101 and i need this 2012-01-01. The problem is that there might be some incorrect inputs like this "2012ABCD". In that case, I want the function to return a fixed date such as 2020-01-01. What I've written so far is:



Create Function ReturnDate
(@date varchar(8))

Returns date

as

begin
declare @result date

set @result = (select convert(date , @date,111))
if(@@ROWCOUNT>0) return @result
else return '2020-01-01'
return @result
end


This doesn't work and I just don't know how to handle the second part (when the input is incorrect).










share|improve this question






























    3















    Hope you're doing well



    I need to write a function to receive a string character and return the date format . For example the input is 20120101 and i need this 2012-01-01. The problem is that there might be some incorrect inputs like this "2012ABCD". In that case, I want the function to return a fixed date such as 2020-01-01. What I've written so far is:



    Create Function ReturnDate
    (@date varchar(8))

    Returns date

    as

    begin
    declare @result date

    set @result = (select convert(date , @date,111))
    if(@@ROWCOUNT>0) return @result
    else return '2020-01-01'
    return @result
    end


    This doesn't work and I just don't know how to handle the second part (when the input is incorrect).










    share|improve this question


























      3












      3








      3








      Hope you're doing well



      I need to write a function to receive a string character and return the date format . For example the input is 20120101 and i need this 2012-01-01. The problem is that there might be some incorrect inputs like this "2012ABCD". In that case, I want the function to return a fixed date such as 2020-01-01. What I've written so far is:



      Create Function ReturnDate
      (@date varchar(8))

      Returns date

      as

      begin
      declare @result date

      set @result = (select convert(date , @date,111))
      if(@@ROWCOUNT>0) return @result
      else return '2020-01-01'
      return @result
      end


      This doesn't work and I just don't know how to handle the second part (when the input is incorrect).










      share|improve this question
















      Hope you're doing well



      I need to write a function to receive a string character and return the date format . For example the input is 20120101 and i need this 2012-01-01. The problem is that there might be some incorrect inputs like this "2012ABCD". In that case, I want the function to return a fixed date such as 2020-01-01. What I've written so far is:



      Create Function ReturnDate
      (@date varchar(8))

      Returns date

      as

      begin
      declare @result date

      set @result = (select convert(date , @date,111))
      if(@@ROWCOUNT>0) return @result
      else return '2020-01-01'
      return @result
      end


      This doesn't work and I just don't know how to handle the second part (when the input is incorrect).







      sql-server t-sql functions






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 3 mins ago









      Tony Hinkle

      3,1151725




      3,1151725










      asked 58 mins ago









      Pantea TourangPantea Tourang

      547




      547




















          1 Answer
          1






          active

          oldest

          votes


















          2














          You can use TRY_CONVERT to check to see if the input can be converted. If it can't, a NULL value is returned so then you can then do an COALESCE to get either the converted value or the fixed date.



          begin
          declare @result date
          set @result = TRY_CONVERT(date, @date, 111)
          set @result = COALESCE(@result, '2012-01-01')
          return @result
          end


          You could also use a TRY CATCH block and return the fixed date in the FINALLY block, but it's best practice to use TRY_CONVERT so that SQL Server doesn't have to handle an error as that requires more time and resources.





          share























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "182"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f236872%2ffunction-to-receive-a-character-input-and-return-date-format-with-incorrect-inp%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            You can use TRY_CONVERT to check to see if the input can be converted. If it can't, a NULL value is returned so then you can then do an COALESCE to get either the converted value or the fixed date.



            begin
            declare @result date
            set @result = TRY_CONVERT(date, @date, 111)
            set @result = COALESCE(@result, '2012-01-01')
            return @result
            end


            You could also use a TRY CATCH block and return the fixed date in the FINALLY block, but it's best practice to use TRY_CONVERT so that SQL Server doesn't have to handle an error as that requires more time and resources.





            share



























              2














              You can use TRY_CONVERT to check to see if the input can be converted. If it can't, a NULL value is returned so then you can then do an COALESCE to get either the converted value or the fixed date.



              begin
              declare @result date
              set @result = TRY_CONVERT(date, @date, 111)
              set @result = COALESCE(@result, '2012-01-01')
              return @result
              end


              You could also use a TRY CATCH block and return the fixed date in the FINALLY block, but it's best practice to use TRY_CONVERT so that SQL Server doesn't have to handle an error as that requires more time and resources.





              share

























                2












                2








                2







                You can use TRY_CONVERT to check to see if the input can be converted. If it can't, a NULL value is returned so then you can then do an COALESCE to get either the converted value or the fixed date.



                begin
                declare @result date
                set @result = TRY_CONVERT(date, @date, 111)
                set @result = COALESCE(@result, '2012-01-01')
                return @result
                end


                You could also use a TRY CATCH block and return the fixed date in the FINALLY block, but it's best practice to use TRY_CONVERT so that SQL Server doesn't have to handle an error as that requires more time and resources.





                share













                You can use TRY_CONVERT to check to see if the input can be converted. If it can't, a NULL value is returned so then you can then do an COALESCE to get either the converted value or the fixed date.



                begin
                declare @result date
                set @result = TRY_CONVERT(date, @date, 111)
                set @result = COALESCE(@result, '2012-01-01')
                return @result
                end


                You could also use a TRY CATCH block and return the fixed date in the FINALLY block, but it's best practice to use TRY_CONVERT so that SQL Server doesn't have to handle an error as that requires more time and resources.






                share











                share


                share










                answered 9 mins ago









                Tony HinkleTony Hinkle

                3,1151725




                3,1151725



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Database Administrators Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f236872%2ffunction-to-receive-a-character-input-and-return-date-format-with-incorrect-inp%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Which organization defines CJK Unified Ideographs? The Next CEO of Stack OverflowCharacters which have several different shapesHow useful are the kanji in reading Chinese?Can Chinese readers scan large amounts of text faster/more accurately than their alphabet-using counterparts?丼: why is “well” also “bowl of food”?What Does Unicode 8.0 Mean For Chinese?How are blanks indicated for placeholders in Chinese (like ???)Is there a dictionary of standard character variants?How to display CJK Extension F?How is it decided as to which character is used on the tech terminology?How does 子 come to mean 'midnight'?

                    Shenzhen Football Club Índice Elenco atual | Títulos | Referências Ligações externas | Menu de navegaçãoGooglenotíciaslivrosacadêmicoeditar«"Elenco"»Site oficialexpandindo-oeee

                    When We Were Young (canção de Adele) Índice Antecedentes e lançamento | Faixas e formatos | Performances e covers | Desempenho nas tabelas musicais | Créditos | Histórico de lançamento | Referências Menu de navegação«Best albums of 2015»«Adele - When We Were Young (Radio Date: 22-01-2016)»«When We Were Young - Single by Adele»«Adele: Inside Her Private Life and Triumphant Return»«adele interview: world exclusive first interview in three years»«Tobias Jesso Jr: since Adele tweeted his song, he's even bigger than his dad»«Adele interviews Tobias Jesso Jr: 'I think that a couple of the ideas we had could be rap songs'»«Adele on Her Return: 'I Was So Frightened That No One Cared'»«Tobias Jesso Jr. on working with Adele: 'I was as nervous as shit'»«How Ariel Rechtshaid Pushed Adele To Her Limit»«Adele Previews 'When We Were Young' on '60 Minutes' Teaser, Tops Trending 140»«Adele Performs New '25' Ballad, "When We Were Young" Live: Watch»«Which '25' Song Should Be Adele's Next Single?»«Adele's 'When We Were Young' Confirmed As Second Single From '25'»«Adele's new single artwork for 'When We Were Young' is perfectly adorable»«Adele at the BBC review: honest, funny and spectacular – Celebrity News News»«'Saturday Night Live': Adele Sings 'Hello' and 'When We Were Young'»«'Adele: Live in New York City' NBC Special – Set List Revealed!»«Adele Closes Out the 2016 Brit Awards With 'When We Were Young'»«What Is The Adele Live Tour Set List? There's No Way She'd Leave Out These 8 Songs»«See Demi Lovato's Soaring Cover of Adele's 'When We Were Young'»«'The Voice': 5 Best Moments From Week 1 Blind Auditions»«Adele – When We Were Young (Media Control Charts)»«Adele – When We Were Young (Entertainment Monitoring Africa)»«Adele – When We Were Young (ARIA Charts)»«Adele – When We Were Young (Ö3 Austria Top 40)»«Adele – When We Were Young (Ultratop 50)»«Adele – When We Were Young (Ultratop 40)»«Adele – When We Were Young (Canadian Hot 100)»«Adele – When We Were Young (Tracklisten)»«Adele – When We Were Young (The Official Charts Company)»«Adele – Hello (IFPI Slovenská Republika)»«Adele – When We Were Young (Productores de Música de España)»«Adele – When We Were Young (Billboard Hot 100)»«Adele – When We Were Young (Pop Songs)»«Adele – When We Were Young (Adult Pop Songs)»«Adele – When We Were Young (Hot Adult Contemporary Charts)»«Adele – When We Were Young (Hot Dance Club Songs)»«Adele – When We Were Young (Rock Airplay)»«Adele – When We Were Young (IFPI Finlândia)»«Adele – When We Were Young (Syndicat National de l'Éditon Phonographique)»«Adele – When We Were Young (Magyar Hanglemezkiadók Szövetsége)»«Adele – When We Were Young (Irish Recorded Music Association)»«Adele – When We Were Young (Mexico Airplay)»«Adele – When We Were Young (VG-lista)»«Adele – When We Were Young (NZ Top 40 Singles)»«Adele – When We Were Young (MegaCharts)»«Adele – When We Were Young (Związek Producentów Audio Video)»«Adele – When We Were Young (Portugal Digital Songs)»«Adele – When We Were Young (UK Indie Singles Chart)»«Adele – When We Were Young (UK Singles Chart)»«Adele – When We Were Young (Sverigetopplistan)»«Adele – When We Were Young (Schweizer Hitparade)»«Adele – When We Were Young (Portugal Digital Songs)»«Music Canada – Gold/Platinum – When We Were Young»«NZ Top 40 Singles Chart»«Certified Awards»e