CAST throwing error when run in stored procedure but not when run as raw querystored procedure with multiple statements does not execute all statements when run from jobSQL Server Replication Monitor Throwing “Specified cast is not valid. (ReplicationMonitor)” ErrorUpdate code works in manual stored procedure but not when run as SQL Server Agent JobCan't cast a stored procedure parameter?ORA-01722 Error when running stored procedureStored Procedure ErrorDelete Works in one Stored Procedure but not anotherStored Procedure: Error 1064MySQL Stored Procedure not throwing error if it contains a query that succeedsSQL Server stored procedure not throwing certain kind of error

Fully-Firstable Anagram Sets

A reference to a well-known characterization of scattered compact spaces

Why is consensus so controversial in Britain?

Western buddy movie with a supernatural twist where a woman turns into an eagle at the end

Is it canonical bit space?

Alternative to sending password over mail?

Facing a paradox: Earnshaw's theorem in one dimension

Can a virus destroy the BIOS of a modern computer?

Twin primes whose sum is a cube

How to prevent "they're falling in love" trope

Today is the Center

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Can one be a co-translator of a book, if he does not know the language that the book is translated into?

Theorems that impeded progress

What exploit are these user agents trying to use?

How can saying a song's name be a copyright violation?

Why can't we play rap on piano?

Has there ever been an airliner design involving reducing generator load by installing solar panels?

Were any external disk drives stacked vertically?

Neighboring nodes in the network

90's TV series where a boy goes to another dimension through portal near power lines

Anagram holiday

Intersection of two sorted vectors in C++

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?



CAST throwing error when run in stored procedure but not when run as raw query


stored procedure with multiple statements does not execute all statements when run from jobSQL Server Replication Monitor Throwing “Specified cast is not valid. (ReplicationMonitor)” ErrorUpdate code works in manual stored procedure but not when run as SQL Server Agent JobCan't cast a stored procedure parameter?ORA-01722 Error when running stored procedureStored Procedure ErrorDelete Works in one Stored Procedure but not anotherStored Procedure: Error 1064MySQL Stored Procedure not throwing error if it contains a query that succeedsSQL Server stored procedure not throwing certain kind of error






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








8















Something very odd is happening here.



I have a query that looks like this.



SELECT CAST(FT.DOP AS SMALLINT) FROM TRACKING_DATA WHERE date > @mydate and identifier = 0000000000


When run as a raw query it returns data just fine.



When i place it in a stored procedure that alters the where clause it throws this error.



Msg 244, Level 16, State 2, Procedure myprocedure, Line 107 [Batch Start Line 2]
The conversion of the varchar value '58629' overflowed an INT2 column. Use a larger integer column.


So here is the oddity. I go through all the possible data for that where clause with a query like this.



SELECT DISTINCT DOP FROM TRACKING_DATA where identifier = 000000000000


and



SELECT DISTINCT CAST(DOP AS smallint) FROM TRACKING_DATA where identifier = 000000000000


And this is what i get back.



17
12
9
19
8
14
6
16
11
13
7
10
0
18
5
15
4


Nowhere does it have anything remotely too large for a SMALLINT. So i thought, ok maybe its a non-printable ASCII character. But i can't find any.



I'm a little perplexed at the moment. It runs find as a raw query, explodes as a procedure and all possible data based on the where is valid. My only suspicion is that the query plan is doing something odd with filtering or maybe runs with different validation when run as a procedure.










share|improve this question






























    8















    Something very odd is happening here.



    I have a query that looks like this.



    SELECT CAST(FT.DOP AS SMALLINT) FROM TRACKING_DATA WHERE date > @mydate and identifier = 0000000000


    When run as a raw query it returns data just fine.



    When i place it in a stored procedure that alters the where clause it throws this error.



    Msg 244, Level 16, State 2, Procedure myprocedure, Line 107 [Batch Start Line 2]
    The conversion of the varchar value '58629' overflowed an INT2 column. Use a larger integer column.


    So here is the oddity. I go through all the possible data for that where clause with a query like this.



    SELECT DISTINCT DOP FROM TRACKING_DATA where identifier = 000000000000


    and



    SELECT DISTINCT CAST(DOP AS smallint) FROM TRACKING_DATA where identifier = 000000000000


    And this is what i get back.



    17
    12
    9
    19
    8
    14
    6
    16
    11
    13
    7
    10
    0
    18
    5
    15
    4


    Nowhere does it have anything remotely too large for a SMALLINT. So i thought, ok maybe its a non-printable ASCII character. But i can't find any.



    I'm a little perplexed at the moment. It runs find as a raw query, explodes as a procedure and all possible data based on the where is valid. My only suspicion is that the query plan is doing something odd with filtering or maybe runs with different validation when run as a procedure.










    share|improve this question


























      8












      8








      8


      1






      Something very odd is happening here.



      I have a query that looks like this.



      SELECT CAST(FT.DOP AS SMALLINT) FROM TRACKING_DATA WHERE date > @mydate and identifier = 0000000000


      When run as a raw query it returns data just fine.



      When i place it in a stored procedure that alters the where clause it throws this error.



      Msg 244, Level 16, State 2, Procedure myprocedure, Line 107 [Batch Start Line 2]
      The conversion of the varchar value '58629' overflowed an INT2 column. Use a larger integer column.


      So here is the oddity. I go through all the possible data for that where clause with a query like this.



      SELECT DISTINCT DOP FROM TRACKING_DATA where identifier = 000000000000


      and



      SELECT DISTINCT CAST(DOP AS smallint) FROM TRACKING_DATA where identifier = 000000000000


      And this is what i get back.



      17
      12
      9
      19
      8
      14
      6
      16
      11
      13
      7
      10
      0
      18
      5
      15
      4


      Nowhere does it have anything remotely too large for a SMALLINT. So i thought, ok maybe its a non-printable ASCII character. But i can't find any.



      I'm a little perplexed at the moment. It runs find as a raw query, explodes as a procedure and all possible data based on the where is valid. My only suspicion is that the query plan is doing something odd with filtering or maybe runs with different validation when run as a procedure.










      share|improve this question
















      Something very odd is happening here.



      I have a query that looks like this.



      SELECT CAST(FT.DOP AS SMALLINT) FROM TRACKING_DATA WHERE date > @mydate and identifier = 0000000000


      When run as a raw query it returns data just fine.



      When i place it in a stored procedure that alters the where clause it throws this error.



      Msg 244, Level 16, State 2, Procedure myprocedure, Line 107 [Batch Start Line 2]
      The conversion of the varchar value '58629' overflowed an INT2 column. Use a larger integer column.


      So here is the oddity. I go through all the possible data for that where clause with a query like this.



      SELECT DISTINCT DOP FROM TRACKING_DATA where identifier = 000000000000


      and



      SELECT DISTINCT CAST(DOP AS smallint) FROM TRACKING_DATA where identifier = 000000000000


      And this is what i get back.



      17
      12
      9
      19
      8
      14
      6
      16
      11
      13
      7
      10
      0
      18
      5
      15
      4


      Nowhere does it have anything remotely too large for a SMALLINT. So i thought, ok maybe its a non-printable ASCII character. But i can't find any.



      I'm a little perplexed at the moment. It runs find as a raw query, explodes as a procedure and all possible data based on the where is valid. My only suspicion is that the query plan is doing something odd with filtering or maybe runs with different validation when run as a procedure.







      sql-server sql-server-2012 stored-procedures






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday







      Chris Rice

















      asked yesterday









      Chris RiceChris Rice

      27116




      27116




















          3 Answers
          3






          active

          oldest

          votes


















          11














          So it was the damn query plan it kept deciding to use.



          The value that it was exploding on was present in the table (which it shouldn't be but that's another problem) but it was associated with a completely different identifier.



          The query in question was running a clustered seek on an index that covered the date but not the identifier this caused it to scan the ENTIRE table which is so, so, so wrong for a number of reasons.



          Added a proper index for the where clause and the procedure is happily humming away now as it filters on the identifier before going after the date. I wish i could get before / after statistics but i'm pretty sure its running faster now too.






          share|improve this answer


















          • 1





            You beat me to your own answer. Sometimes stored procedures use different query plans than simple ad-hoc queries, and this can result in the system processing data in a different order. Usually, indexing is a good workaround, but sometimes you need to move the last operation outside of the data retrieval for things to work, i.e. SELECT CAST(FT.DOP AS SMALLINT) FROM (SELECT FT.DOP FROM TRACKING_DATA WHERE date > @mydate and identifier = 000000) As FT

            – Laughing Vergil
            yesterday






          • 1





            @LaughingVergil - That is not guaranteed to work. The CAST can still get pushed before the filter, the most reliable way is to use TRY_CONVERT so then it doesn't matter if it runs against rows that would fail the cast but later be eliminated anyway

            – Martin Smith
            yesterday


















          11














          You're better off not depending on the indexing to avoid these errors, and instead writing the query to guard against this situation. Since you're on SQL Server 2012, one option would be to use TRY_CAST:



          SELECT TRY_CAST(FT.DOP AS SMALLINT) 
          FROM TRACKING_DATA
          WHERE date > @mydate and identifier = 0000000000;


          This will result in NULL being selected for values that fail to convert from varchar to smallint. But as long as you know there aren't any results like that, or your application can handle the NULL results, you should be good.






          share|improve this answer






























            0














            You are obviously getting different query plans and your cast is being tried against values which are filtered out by the where clause, I wouldn’t bother trying to figure out why — whatever the cause, it could obviously happen for a different reason later. Relying upon filtering is unreliable.



            The thing to do is to write a query that won’t fail regardless of any index, hint, or statistics.



            I think there are 3 ways to do this:




            1. Use a temp table/table variable.



              declare @result table (dop varchar);
              Insert into @result
              SELECT FT.DOP FROM TRACKING_DATA
              WHERE date > @mydate and identifier = 0000000000

              SELECT cast(dop as SMALLINT) dop from @result



            2. Use a case statement:



              SELECT CAST(case when FT.DOP like '%[^0-9]%' then null else ft.dop end AS SMALLINT) 
              FROM TRACKING_DATA
              WHERE date > @mydate and identifier = 0000000000



            3. Use try_cast instead and of cast:



              SELECT try_CAST(FT.DOP AS SMALLINT) 
              FROM TRACKING_DATA
              WHERE date > @mydate and identifier = 0000000000


            Personally I would recommend 3 if possible.






            share|improve this answer























              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%2f233851%2fcast-throwing-error-when-run-in-stored-procedure-but-not-when-run-as-raw-query%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              11














              So it was the damn query plan it kept deciding to use.



              The value that it was exploding on was present in the table (which it shouldn't be but that's another problem) but it was associated with a completely different identifier.



              The query in question was running a clustered seek on an index that covered the date but not the identifier this caused it to scan the ENTIRE table which is so, so, so wrong for a number of reasons.



              Added a proper index for the where clause and the procedure is happily humming away now as it filters on the identifier before going after the date. I wish i could get before / after statistics but i'm pretty sure its running faster now too.






              share|improve this answer


















              • 1





                You beat me to your own answer. Sometimes stored procedures use different query plans than simple ad-hoc queries, and this can result in the system processing data in a different order. Usually, indexing is a good workaround, but sometimes you need to move the last operation outside of the data retrieval for things to work, i.e. SELECT CAST(FT.DOP AS SMALLINT) FROM (SELECT FT.DOP FROM TRACKING_DATA WHERE date > @mydate and identifier = 000000) As FT

                – Laughing Vergil
                yesterday






              • 1





                @LaughingVergil - That is not guaranteed to work. The CAST can still get pushed before the filter, the most reliable way is to use TRY_CONVERT so then it doesn't matter if it runs against rows that would fail the cast but later be eliminated anyway

                – Martin Smith
                yesterday















              11














              So it was the damn query plan it kept deciding to use.



              The value that it was exploding on was present in the table (which it shouldn't be but that's another problem) but it was associated with a completely different identifier.



              The query in question was running a clustered seek on an index that covered the date but not the identifier this caused it to scan the ENTIRE table which is so, so, so wrong for a number of reasons.



              Added a proper index for the where clause and the procedure is happily humming away now as it filters on the identifier before going after the date. I wish i could get before / after statistics but i'm pretty sure its running faster now too.






              share|improve this answer


















              • 1





                You beat me to your own answer. Sometimes stored procedures use different query plans than simple ad-hoc queries, and this can result in the system processing data in a different order. Usually, indexing is a good workaround, but sometimes you need to move the last operation outside of the data retrieval for things to work, i.e. SELECT CAST(FT.DOP AS SMALLINT) FROM (SELECT FT.DOP FROM TRACKING_DATA WHERE date > @mydate and identifier = 000000) As FT

                – Laughing Vergil
                yesterday






              • 1





                @LaughingVergil - That is not guaranteed to work. The CAST can still get pushed before the filter, the most reliable way is to use TRY_CONVERT so then it doesn't matter if it runs against rows that would fail the cast but later be eliminated anyway

                – Martin Smith
                yesterday













              11












              11








              11







              So it was the damn query plan it kept deciding to use.



              The value that it was exploding on was present in the table (which it shouldn't be but that's another problem) but it was associated with a completely different identifier.



              The query in question was running a clustered seek on an index that covered the date but not the identifier this caused it to scan the ENTIRE table which is so, so, so wrong for a number of reasons.



              Added a proper index for the where clause and the procedure is happily humming away now as it filters on the identifier before going after the date. I wish i could get before / after statistics but i'm pretty sure its running faster now too.






              share|improve this answer













              So it was the damn query plan it kept deciding to use.



              The value that it was exploding on was present in the table (which it shouldn't be but that's another problem) but it was associated with a completely different identifier.



              The query in question was running a clustered seek on an index that covered the date but not the identifier this caused it to scan the ENTIRE table which is so, so, so wrong for a number of reasons.



              Added a proper index for the where clause and the procedure is happily humming away now as it filters on the identifier before going after the date. I wish i could get before / after statistics but i'm pretty sure its running faster now too.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered yesterday









              Chris RiceChris Rice

              27116




              27116







              • 1





                You beat me to your own answer. Sometimes stored procedures use different query plans than simple ad-hoc queries, and this can result in the system processing data in a different order. Usually, indexing is a good workaround, but sometimes you need to move the last operation outside of the data retrieval for things to work, i.e. SELECT CAST(FT.DOP AS SMALLINT) FROM (SELECT FT.DOP FROM TRACKING_DATA WHERE date > @mydate and identifier = 000000) As FT

                – Laughing Vergil
                yesterday






              • 1





                @LaughingVergil - That is not guaranteed to work. The CAST can still get pushed before the filter, the most reliable way is to use TRY_CONVERT so then it doesn't matter if it runs against rows that would fail the cast but later be eliminated anyway

                – Martin Smith
                yesterday












              • 1





                You beat me to your own answer. Sometimes stored procedures use different query plans than simple ad-hoc queries, and this can result in the system processing data in a different order. Usually, indexing is a good workaround, but sometimes you need to move the last operation outside of the data retrieval for things to work, i.e. SELECT CAST(FT.DOP AS SMALLINT) FROM (SELECT FT.DOP FROM TRACKING_DATA WHERE date > @mydate and identifier = 000000) As FT

                – Laughing Vergil
                yesterday






              • 1





                @LaughingVergil - That is not guaranteed to work. The CAST can still get pushed before the filter, the most reliable way is to use TRY_CONVERT so then it doesn't matter if it runs against rows that would fail the cast but later be eliminated anyway

                – Martin Smith
                yesterday







              1




              1





              You beat me to your own answer. Sometimes stored procedures use different query plans than simple ad-hoc queries, and this can result in the system processing data in a different order. Usually, indexing is a good workaround, but sometimes you need to move the last operation outside of the data retrieval for things to work, i.e. SELECT CAST(FT.DOP AS SMALLINT) FROM (SELECT FT.DOP FROM TRACKING_DATA WHERE date > @mydate and identifier = 000000) As FT

              – Laughing Vergil
              yesterday





              You beat me to your own answer. Sometimes stored procedures use different query plans than simple ad-hoc queries, and this can result in the system processing data in a different order. Usually, indexing is a good workaround, but sometimes you need to move the last operation outside of the data retrieval for things to work, i.e. SELECT CAST(FT.DOP AS SMALLINT) FROM (SELECT FT.DOP FROM TRACKING_DATA WHERE date > @mydate and identifier = 000000) As FT

              – Laughing Vergil
              yesterday




              1




              1





              @LaughingVergil - That is not guaranteed to work. The CAST can still get pushed before the filter, the most reliable way is to use TRY_CONVERT so then it doesn't matter if it runs against rows that would fail the cast but later be eliminated anyway

              – Martin Smith
              yesterday





              @LaughingVergil - That is not guaranteed to work. The CAST can still get pushed before the filter, the most reliable way is to use TRY_CONVERT so then it doesn't matter if it runs against rows that would fail the cast but later be eliminated anyway

              – Martin Smith
              yesterday













              11














              You're better off not depending on the indexing to avoid these errors, and instead writing the query to guard against this situation. Since you're on SQL Server 2012, one option would be to use TRY_CAST:



              SELECT TRY_CAST(FT.DOP AS SMALLINT) 
              FROM TRACKING_DATA
              WHERE date > @mydate and identifier = 0000000000;


              This will result in NULL being selected for values that fail to convert from varchar to smallint. But as long as you know there aren't any results like that, or your application can handle the NULL results, you should be good.






              share|improve this answer



























                11














                You're better off not depending on the indexing to avoid these errors, and instead writing the query to guard against this situation. Since you're on SQL Server 2012, one option would be to use TRY_CAST:



                SELECT TRY_CAST(FT.DOP AS SMALLINT) 
                FROM TRACKING_DATA
                WHERE date > @mydate and identifier = 0000000000;


                This will result in NULL being selected for values that fail to convert from varchar to smallint. But as long as you know there aren't any results like that, or your application can handle the NULL results, you should be good.






                share|improve this answer

























                  11












                  11








                  11







                  You're better off not depending on the indexing to avoid these errors, and instead writing the query to guard against this situation. Since you're on SQL Server 2012, one option would be to use TRY_CAST:



                  SELECT TRY_CAST(FT.DOP AS SMALLINT) 
                  FROM TRACKING_DATA
                  WHERE date > @mydate and identifier = 0000000000;


                  This will result in NULL being selected for values that fail to convert from varchar to smallint. But as long as you know there aren't any results like that, or your application can handle the NULL results, you should be good.






                  share|improve this answer













                  You're better off not depending on the indexing to avoid these errors, and instead writing the query to guard against this situation. Since you're on SQL Server 2012, one option would be to use TRY_CAST:



                  SELECT TRY_CAST(FT.DOP AS SMALLINT) 
                  FROM TRACKING_DATA
                  WHERE date > @mydate and identifier = 0000000000;


                  This will result in NULL being selected for values that fail to convert from varchar to smallint. But as long as you know there aren't any results like that, or your application can handle the NULL results, you should be good.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered yesterday









                  Josh DarnellJosh Darnell

                  7,75022242




                  7,75022242





















                      0














                      You are obviously getting different query plans and your cast is being tried against values which are filtered out by the where clause, I wouldn’t bother trying to figure out why — whatever the cause, it could obviously happen for a different reason later. Relying upon filtering is unreliable.



                      The thing to do is to write a query that won’t fail regardless of any index, hint, or statistics.



                      I think there are 3 ways to do this:




                      1. Use a temp table/table variable.



                        declare @result table (dop varchar);
                        Insert into @result
                        SELECT FT.DOP FROM TRACKING_DATA
                        WHERE date > @mydate and identifier = 0000000000

                        SELECT cast(dop as SMALLINT) dop from @result



                      2. Use a case statement:



                        SELECT CAST(case when FT.DOP like '%[^0-9]%' then null else ft.dop end AS SMALLINT) 
                        FROM TRACKING_DATA
                        WHERE date > @mydate and identifier = 0000000000



                      3. Use try_cast instead and of cast:



                        SELECT try_CAST(FT.DOP AS SMALLINT) 
                        FROM TRACKING_DATA
                        WHERE date > @mydate and identifier = 0000000000


                      Personally I would recommend 3 if possible.






                      share|improve this answer



























                        0














                        You are obviously getting different query plans and your cast is being tried against values which are filtered out by the where clause, I wouldn’t bother trying to figure out why — whatever the cause, it could obviously happen for a different reason later. Relying upon filtering is unreliable.



                        The thing to do is to write a query that won’t fail regardless of any index, hint, or statistics.



                        I think there are 3 ways to do this:




                        1. Use a temp table/table variable.



                          declare @result table (dop varchar);
                          Insert into @result
                          SELECT FT.DOP FROM TRACKING_DATA
                          WHERE date > @mydate and identifier = 0000000000

                          SELECT cast(dop as SMALLINT) dop from @result



                        2. Use a case statement:



                          SELECT CAST(case when FT.DOP like '%[^0-9]%' then null else ft.dop end AS SMALLINT) 
                          FROM TRACKING_DATA
                          WHERE date > @mydate and identifier = 0000000000



                        3. Use try_cast instead and of cast:



                          SELECT try_CAST(FT.DOP AS SMALLINT) 
                          FROM TRACKING_DATA
                          WHERE date > @mydate and identifier = 0000000000


                        Personally I would recommend 3 if possible.






                        share|improve this answer

























                          0












                          0








                          0







                          You are obviously getting different query plans and your cast is being tried against values which are filtered out by the where clause, I wouldn’t bother trying to figure out why — whatever the cause, it could obviously happen for a different reason later. Relying upon filtering is unreliable.



                          The thing to do is to write a query that won’t fail regardless of any index, hint, or statistics.



                          I think there are 3 ways to do this:




                          1. Use a temp table/table variable.



                            declare @result table (dop varchar);
                            Insert into @result
                            SELECT FT.DOP FROM TRACKING_DATA
                            WHERE date > @mydate and identifier = 0000000000

                            SELECT cast(dop as SMALLINT) dop from @result



                          2. Use a case statement:



                            SELECT CAST(case when FT.DOP like '%[^0-9]%' then null else ft.dop end AS SMALLINT) 
                            FROM TRACKING_DATA
                            WHERE date > @mydate and identifier = 0000000000



                          3. Use try_cast instead and of cast:



                            SELECT try_CAST(FT.DOP AS SMALLINT) 
                            FROM TRACKING_DATA
                            WHERE date > @mydate and identifier = 0000000000


                          Personally I would recommend 3 if possible.






                          share|improve this answer













                          You are obviously getting different query plans and your cast is being tried against values which are filtered out by the where clause, I wouldn’t bother trying to figure out why — whatever the cause, it could obviously happen for a different reason later. Relying upon filtering is unreliable.



                          The thing to do is to write a query that won’t fail regardless of any index, hint, or statistics.



                          I think there are 3 ways to do this:




                          1. Use a temp table/table variable.



                            declare @result table (dop varchar);
                            Insert into @result
                            SELECT FT.DOP FROM TRACKING_DATA
                            WHERE date > @mydate and identifier = 0000000000

                            SELECT cast(dop as SMALLINT) dop from @result



                          2. Use a case statement:



                            SELECT CAST(case when FT.DOP like '%[^0-9]%' then null else ft.dop end AS SMALLINT) 
                            FROM TRACKING_DATA
                            WHERE date > @mydate and identifier = 0000000000



                          3. Use try_cast instead and of cast:



                            SELECT try_CAST(FT.DOP AS SMALLINT) 
                            FROM TRACKING_DATA
                            WHERE date > @mydate and identifier = 0000000000


                          Personally I would recommend 3 if possible.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered yesterday









                          jmorenojmoreno

                          644516




                          644516



























                              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%2f233851%2fcast-throwing-error-when-run-in-stored-procedure-but-not-when-run-as-raw-query%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

                              Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                              Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

                              Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?