CAST throwing error when run in stored procedure but not when run as raw query [duplicate]Why does query error with empty result set in SQL Server 2012?At which point does SQL Server validate data for insertionIntermittent “Conversion failed…” errorUPDATE statement processing records that should be eliminated by WHERE clauseImplicit conversion causing error part of the timestored 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

Fencing style for blades that can attack from a distance

An academic/student plagiarism

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

"You are your self first supporter", a more proper way to say it

If I cast Expeditious Retreat, can I Dash as a bonus action on the same turn?

Mathematical cryptic clues

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

How can bays and straits be determined in a procedurally generated map?

Python: next in for loop

strToHex ( string to its hex representation as string)

What do the dots in this tr command do: tr .............A-Z A-ZA-Z <<< "JVPQBOV" (with 13 dots)

Can divisibility rules for digits be generalized to sum of digits

Which models of the Boeing 737 are still in production?

To string or not to string

Why are electrically insulating heatsinks so rare? Is it just cost?

Did Shadowfax go to Valinor?

Why do falling prices hurt debtors?

Can I ask the recruiters in my resume to put the reason why I am rejected?

What are the differences between the usage of 'it' and 'they'?

Maximum likelihood parameters deviate from posterior distributions

Why Is Death Allowed In the Matrix?

Why does Kotter return in Welcome Back Kotter?

Is this a crack on the carbon frame?

Has the BBC provided arguments for saying Brexit being cancelled is unlikely?



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


Why does query error with empty result set in SQL Server 2012?At which point does SQL Server validate data for insertionIntermittent “Conversion failed…” errorUPDATE statement processing records that should be eliminated by WHERE clauseImplicit conversion causing error part of the timestored 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
















This question already has an answer here:



  • At which point does SQL Server validate data for insertion

    1 answer



  • Implicit conversion causing error part of the time

    1 answer



  • UPDATE statement processing records that should be eliminated by WHERE clause

    1 answer



  • Intermittent “Conversion failed…” error

    1 answer



  • Why does query error with empty result set in SQL Server 2012?

    2 answers



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















marked as duplicate by Paul White sql-server
Users with the  sql-server badge can single-handedly close sql-server questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
yesterday


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
























    8
















    This question already has an answer here:



    • At which point does SQL Server validate data for insertion

      1 answer



    • Implicit conversion causing error part of the time

      1 answer



    • UPDATE statement processing records that should be eliminated by WHERE clause

      1 answer



    • Intermittent “Conversion failed…” error

      1 answer



    • Why does query error with empty result set in SQL Server 2012?

      2 answers



    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















    marked as duplicate by Paul White sql-server
    Users with the  sql-server badge can single-handedly close sql-server questions as duplicates and reopen them as needed.

    StackExchange.ready(function()
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function()
    $hover.showInfoMessage('',
    messageElement: $msg.clone().show(),
    transient: false,
    position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
    dismissable: false,
    relativeToBody: true
    );
    ,
    function()
    StackExchange.helpers.removeMessages();

    );
    );
    );
    yesterday


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




















      8












      8








      8


      1







      This question already has an answer here:



      • At which point does SQL Server validate data for insertion

        1 answer



      • Implicit conversion causing error part of the time

        1 answer



      • UPDATE statement processing records that should be eliminated by WHERE clause

        1 answer



      • Intermittent “Conversion failed…” error

        1 answer



      • Why does query error with empty result set in SQL Server 2012?

        2 answers



      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

















      This question already has an answer here:



      • At which point does SQL Server validate data for insertion

        1 answer



      • Implicit conversion causing error part of the time

        1 answer



      • UPDATE statement processing records that should be eliminated by WHERE clause

        1 answer



      • Intermittent “Conversion failed…” error

        1 answer



      • Why does query error with empty result set in SQL Server 2012?

        2 answers



      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.





      This question already has an answer here:



      • At which point does SQL Server validate data for insertion

        1 answer



      • Implicit conversion causing error part of the time

        1 answer



      • UPDATE statement processing records that should be eliminated by WHERE clause

        1 answer



      • Intermittent “Conversion failed…” error

        1 answer



      • Why does query error with empty result set in SQL Server 2012?

        2 answers







      sql-server sql-server-2012 stored-procedures






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 3 at 18:39







      Chris Rice

















      asked Apr 3 at 15:55









      Chris RiceChris Rice

      27116




      27116




      marked as duplicate by Paul White sql-server
      Users with the  sql-server badge can single-handedly close sql-server questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      yesterday


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









      marked as duplicate by Paul White sql-server
      Users with the  sql-server badge can single-handedly close sql-server questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      yesterday


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






















          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
            Apr 3 at 16:15






          • 2





            @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
            Apr 3 at 16:37


















          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






























            1














            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





























              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
                Apr 3 at 16:15






              • 2





                @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
                Apr 3 at 16:37















              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
                Apr 3 at 16:15






              • 2





                @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
                Apr 3 at 16:37













              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 Apr 3 at 16:10









              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
                Apr 3 at 16:15






              • 2





                @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
                Apr 3 at 16:37












              • 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
                Apr 3 at 16:15






              • 2





                @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
                Apr 3 at 16:37







              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
              Apr 3 at 16:15





              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
              Apr 3 at 16:15




              2




              2





              @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
              Apr 3 at 16:37





              @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
              Apr 3 at 16:37













              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 Apr 3 at 16:38









                  Josh DarnellJosh Darnell

                  7,84022243




                  7,84022243





















                      1














                      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



























                        1














                        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

























                          1












                          1








                          1







                          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 Apr 4 at 1:54









                          jmorenojmoreno

                          654516




                          654516













                              Popular posts from this blog

                              Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                              Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

                              Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020