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

Is it acceptable for a professor to tell male students to not think that they are smarter than female students?

How do I handle a potential work/personal life conflict as the manager of one of my friends?

What type of content (depth/breadth) is expected for a short presentation for Asst Professor interview in the UK?

Alternative to sending password over mail?

Why can't we play rap on piano?

Venezuelan girlfriend wants to travel the USA to be with me. What is the process?

Is it logically or scientifically possible to artificially send energy to the body?

Is "remove commented out code" correct English?

What is the idiomatic way to say "clothing fits"?

Short story with a alien planet, government officials must wear exploding medallions

How dangerous is XSS?

Which is the best way to check return result?

What about the virus in 12 Monkeys?

Can compressed videos be decoded back to their uncompresed original format?

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

Is there a hemisphere-neutral way of specifying a season?

Why was the shrinking from 8″ made only to 5.25″ and not smaller (4″ or less)?

Why would the Red Woman birth a shadow if she worshipped the Lord of the Light?

Bullying boss launched a smear campaign and made me unemployable

Do UK voters know if their MP will be the Speaker of the House?

Can my sorcerer use a spellbook only to collect spells and scribe scrolls, not cast?

Why no variance term in Bayesian logistic regression?

Is this a hacking script in function.php?

What do you call someone who asks many questions?



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













6















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




























    6















    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


























      6












      6








      6








      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 5 hours ago







      Chris Rice

















      asked 8 hours ago









      Chris RiceChris Rice

      21115




      21115




















          2 Answers
          2






          active

          oldest

          votes


















          8














          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























          • I think this is the solution for the query in addition to the index. I made this ugly CASE WHEN > max_value before and this is so much more elegant.

            – Chris Rice
            5 hours ago











          • @ChrisRice It's funny you say that, that's exactly what I started typing at first too!

            – Josh Darnell
            4 hours ago


















          6














          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
            8 hours ago






          • 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
            7 hours ago











          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

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8














          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























          • I think this is the solution for the query in addition to the index. I made this ugly CASE WHEN > max_value before and this is so much more elegant.

            – Chris Rice
            5 hours ago











          • @ChrisRice It's funny you say that, that's exactly what I started typing at first too!

            – Josh Darnell
            4 hours ago















          8














          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























          • I think this is the solution for the query in addition to the index. I made this ugly CASE WHEN > max_value before and this is so much more elegant.

            – Chris Rice
            5 hours ago











          • @ChrisRice It's funny you say that, that's exactly what I started typing at first too!

            – Josh Darnell
            4 hours ago













          8












          8








          8







          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 7 hours ago









          Josh DarnellJosh Darnell

          7,60022241




          7,60022241












          • I think this is the solution for the query in addition to the index. I made this ugly CASE WHEN > max_value before and this is so much more elegant.

            – Chris Rice
            5 hours ago











          • @ChrisRice It's funny you say that, that's exactly what I started typing at first too!

            – Josh Darnell
            4 hours ago

















          • I think this is the solution for the query in addition to the index. I made this ugly CASE WHEN > max_value before and this is so much more elegant.

            – Chris Rice
            5 hours ago











          • @ChrisRice It's funny you say that, that's exactly what I started typing at first too!

            – Josh Darnell
            4 hours ago
















          I think this is the solution for the query in addition to the index. I made this ugly CASE WHEN > max_value before and this is so much more elegant.

          – Chris Rice
          5 hours ago





          I think this is the solution for the query in addition to the index. I made this ugly CASE WHEN > max_value before and this is so much more elegant.

          – Chris Rice
          5 hours ago













          @ChrisRice It's funny you say that, that's exactly what I started typing at first too!

          – Josh Darnell
          4 hours ago





          @ChrisRice It's funny you say that, that's exactly what I started typing at first too!

          – Josh Darnell
          4 hours ago













          6














          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
            8 hours ago






          • 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
            7 hours ago















          6














          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
            8 hours ago






          • 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
            7 hours ago













          6












          6








          6







          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 8 hours ago









          Chris RiceChris Rice

          21115




          21115







          • 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
            8 hours ago






          • 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
            7 hours ago












          • 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
            8 hours ago






          • 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
            7 hours ago







          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
          8 hours ago





          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
          8 hours ago




          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
          7 hours ago





          @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
          7 hours ago

















          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

          How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

          Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

          Category:Tremithousa Media in category "Tremithousa"Navigation menuUpload media34° 49′ 02.7″ N, 32° 26′ 37.32″ EOpenStreetMapGoogle EarthProximityramaReasonatorScholiaStatisticsWikiShootMe