Saving result from sp_executesql into a variable and using dynamic column name - getting error "Error converting data type varchar to numeric"

Im getting an error when running a procedure that includes this code.
I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql
DECLARE @retval AS DECIMAL(12,2)
DECLARE @MonthVal VARCHAR(20), @SpreadKeyVal INT
DECLARE @sqlcmd AS NVARCHAR(150)
DECLARE @paramdef NVARCHAR(150)
SET @MonthVal = 'Month' + CAST(@MonthNumber AS VARCHAR(2) );
SET @SpreadKeyVal = @SpreadKey; --CAST(@SpreadKey AS VARCHAR(10) );
SET @sqlcmd = N' SELECT @retvalout = @MonthVal FROM dbo.CourseSpread WHERE CourseSpreadId = @SpreadKeyVal';
SET @paramdef = N'@MonthVal VARCHAR(20), @SpreadKeyVal INT, @retvalout DECIMAL(12,2) OUTPUT'
--default
SET @retval = 0.0;
EXECUTE sys.sp_executesql @sqlcmd,@paramdef, @MonthVal = 'Month4',@SpreadKeyVal = 1, @retvalout = @retval OUTPUT;
SELECT @retval
DECLARE @return_value DECIMAL(12,2)
EXEC @return_value = [dbo].[GetSpreadValueByMonthNumber]
@SpreadKey = 1,
@MonthNumber = 4
SELECT 'Return Value' = @return_value
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.

Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
>> I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql <<
This is so very, very wrong! A column is an attribute of an entity. The idea that you are so screwed up that you have no idea if you want
the shoe size, the phone number or something else at run time of this entity. 
In Software Engineering we have a principle called cohesion that says a model should do one and only one task, have one and only one entry point, and one and only one exit point. 
Hey, on a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, your mindset is that level of sillyity and absurdity. 
Do you know that SQL is a declarative language? This family of languages does not use local variables! 
Now think about “month_val” and what it means. A month is a temporal unit of measurement, so this is as silly as saying “liter_val” in your code. Why did you use “sp_” on a procedure? It has special meaning in T-SQL.  
Think about how silly this is: 
 SET @month_val = 'Month' + CAST(@month_nbr AS VARCHAR(2));
We do not do display formatting in a query. This is a violation of at the tiered architecture principle. We have a presentation layer. But more than that, the INTERVAL temporal data type is a {year-month} and never just a month. This is fundamental. 
We need to see the DDL so we can re-write this mess. Want to fix it or not?
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Transpose Distinct Date and Use as Column name

    All,
    I am trying to transpose a distinct date and use it as a column name and list the data below it. My version of Oracle does not have the pivot function. Plus I am having trouble with figuring out how to alter the table name to the distinct date. Can someone provide me with logic that will dynamically take the current format (see below) and transpose it to the needed format (see below)?
    Current format:
    WEEK_END_DATE     RD     STORE_NUMBER     RANK
    09-19-2009     R0011     00505     6
    09-19-2009     R0028     00097     97
    09-19-2009     R0057     01801     72
    09-19-2009     R0061     04775     72
    09-19-2009     R0068     03920     66
    09-26-2009     R0011     00505     8
    09-26-2009     R0028     00097     50
    09-26-2009     R0057     01801     120
    09-26-2009     R0061     04775     30
    09-26-2009     R0068     03920     1
    nth date
    The format I need:
    RD     STORE_NUMBER     09-19-2009 09-26-2009 nth date....
    R0011     00505     6 8
    R0028     00097     97 50
    R0057     01801     72 120
    R0061     04775     72 30
    R0068     03920     66 1

    I apprreciate your help. I have tried to implement the dynamic pivot logic. I can create the correct case statement and change the column name to the name I need.
    However, when I try to use @@dynamic_pivot.sql I get the following error:
    ORA-04054: database link ORAEDW@DYNAMIC_PIVOT_SUBSCRIPT does not exist
    I have tried it three ways...
    @@dynamic_pivot
    and @@dynamic_pivot.sql
    and @@c:\dynamic_pivot_subscript.sql
    I don't have direct access to the database. I have to run my queries from toad. When I cut and paste the generated case statements, It works. I am just not able to dynamiclly insert those case statements into a select. Do you have any suggestion?
    -- ***** Start of dynamic_pivot.sql *****
    -- Suppress SQL*Plus features that interfere with raw output
    set feedback off;
    set heading off;
    SPOOL     c:\dynamic_pivot_subscript.sql
    SELECT
    DISTINCT',max(CASE WHEN week_end_date = '''|| week_end_date || ''' THEN rank END) AS '|| 'DATE_AS_OF_' ||
    to_char(week_end_date,'MM_DD_YYYY') AS case
    FROM
    test_ptw_bottom_10;
    SPOOL OFF
    -- Restore SQL*Plus features suppressed earlier
    What I need:
    SELECT     
    rd,
    store_number
    @@c:\dynamic_pivot_subscript.sql
    FROM     
    test_ptw_bottom_10
    where
    week_end_date in ('19-SEP-09','26-sep09')
    group by
    rd,store_number
    ORDER BY     
    rd;
    What works:
    SELECT     
    rd,
    store_number
    ,max(CASE WHEN week_end_date = '26-SEP-09' THEN rank END) AS DATE_AS_OF_09_26_2009
    ,max(CASE WHEN week_end_date = '19-SEP-09' THEN rank END) AS DATE_AS_OF_09_19_2009
    FROM     
    test_ptw_bottom_10
    where
    week_end_date in ('19-SEP-09','26-sep09')
    group by
    rd,store_number
    ORDER BY     
    rd;
    Edited by: user10609947 on Oct 5, 2009 2:36 PM
    Edited by: user10609947 on Oct 5, 2009 2:38 PM

  • Saving result from query into CSV file

    Hi folks,
    in our application we're generating pages source using general packages (like htp, owa_util, ...). and in this part I'm a really beginner.
    I want to modify source one of our page, I want to add functionality to enable save result from query (cursor) into CSV file, to enable user choose place where generated file will be created and also change file name.
    I searched this forum and I found procedure, that could be useful:
    procedure p_getcsv is
    cursor cur is
           select 'a1' col1, 'b1' col2, 'c1' col3 from dual
       union  select 'a2' col1, 'b2' col2, 'c2' col3 from dual
       union  select 'a3' col1, 'b3' col2, 'c3' col3 from dual;
       begin
            -- Set the MIME type
            owa_util.mime_header( 'application/octet', FALSE );
            -- Set the name of the file
            htp.p('Content-Disposition: attachment; filename="test.csv"');
            -- Close the HTTP Header
            owa_util.http_header_close;
            -- Loop through all rows in EMP
            for x in cur
            loop
                -- Print out a portion of a row,
                -- separated by commas and ended by a CR
                 htp.prn(x.col1||','|| x.col2||','||x.col3|| chr(13));
            end loop;        
       end;What peace of code should I add to procedure that is generating web page to enable calling this procedure and whole saving process?
    Can anybody help me with this?
    Many thanks,
    Tomas
    Message was edited by:
    Tomeo

    Hi Marc,
    thanks for reply, problem is that I'm not using APEX application, I'm just generating web page code straight using oracle general packages.
    But I found this solution (maybe some tunning will be good):
    In page where I want to display Download i have
      begin
             htp.anchor2 (
                           curl  =>  ... .p_getcsv'||'?term=2005&crn=123,
                           ctext => 'Download Class List'
             HTP.br;
          end;
    ...si I'm calling p_getcsv procedure:
      procedure p_getcsv( term  IN stvterm.stvterm_code%TYPE DEFAULT NULL,
                           crn   IN sirasgn.sirasgn_crn%TYPE DEFAULT NULL) is
       v_length      NUMBER;
       v_file_name   VARCHAR2 (2000);
       temp_blob  blob;
       line RAW(32767);
       begin
             DBMS_LOB.CREATETEMPORARY(temp_blob, TRUE);
             FOR i IN 1..6  LOOP
                line := UTL_RAW.CAST_TO_RAW(i||','||term||','||crn||',AAA,BBB,CCC'||chr(10));
                DBMS_LOB.WRITEAPPEND(temp_blob, LENGTH(UTL_RAW.CAST_TO_VARCHAR2(line)), line);
             END LOOP;
              v_file_name := 'ClassList.csv';
              v_length  := DBMS_LOB.getlength (temp_blob);
              -- set up HTTP header
                 -- use an NVL around the mime type and
                 -- if it is a null set it to application/octect
                 -- application/octect may launch a download window from windows
               OWA_UTIL.mime_header (NVL ('csv', 'application/octet'), FALSE);
               -- set the size so the browser knows how much to download
               HTP.p ('Content-length: ' || v_length);
               -- the filename will be used by the browser if the users does a save as
               HTP.p (   'Content-Disposition:  attachment; filename="'
                  || REPLACE (REPLACE (SUBSTR (v_file_name,
                                               INSTR (v_file_name, '/') + 1
                                       CHR (10),
                                       NULL
                              CHR (13),
                              NULL
                  || '"'
                 -- close the headers
                 OWA_UTIL.http_header_close;
                -- download the BLOB
                 WPG_DOCLOAD.download_file (temp_blob);
                 -- release temporary blob
                 dbms_lob.freetemporary(temp_blob);  
       end;Regards,
    Tomas

  • XML Publisher, define variable and use out side the group

    Hi
    Is there any way that I can define a variable in the group and move XML data like line amount into that variable and use into outside the group.
    Regards
    ASIM

    I figured it out
    in your select if you want to group your output by say Organization_id change your select in your burst file to the following
    <xapi:request select="/PAYSLIP_REPORT/PAYSLIP/EMPLOYEE_DETAILS/ORGANIZATION_ID">

  • I'm trying to transfer my pictures from my iPhoto library to my external hard drive. I dragged the iPhoto Library folder into the drive and after waiting a while it says Error Code -36. I need to free up space asap, what should i do?

    I'm trying to transfer my pictures from my iPhoto library to my external hard drive. I dragged the iPhoto Library folder into the drive and after waiting a while it says "Error Code -36 The finder cannot complete the operation because some data in 'iPhoto Library' could not be read or written". I need to free up space asap, what should i do??

    Yes, the Old Master file has a folder for each year where I find all photos from that specific year. I am attaching a screen shot of the file.
    In the meantime i have managed to download all photos (it did not download any video files though in mpg, avi, 3gp, m4v,mp4 and mov format) to a new iphoto library. Unfortunately the photos are quite mixed and often doubled up. I ma considering to purchase iphoto library which checks all duplicates in iphoto. this will save me a lot of time. What do you think?

  • HT203175 I downloaded two videos from itunes into Media Go and I can't play or transfer them to my Walkman. Please help. I'm new at this and haven't a clue as to what I should do. Is Media Go the wrong place to put the videos? Thanks. Earl G.

    I downloaded two videos from itunes into Media Go and I can't play or transfer them to my Walkman. Please help. I'm new at this and haven't a clue as to what I should do. Is Media Go the wrong place to put the videos? Thanks. Earl G.

    I was able to transfer songs, but not the videos. You, too? Earl. G.

  • Trying to click and drop photos from iPhoto into an Empty SD card. all I am getting isThe item "IMG_0346.JPG" can't be copied because there isn't enough free space. Card is 156 MB Photo is 1.56MB. Help please.

    Trying to click and drop photos from iPhoto into an Empty SD card. all I am getting isThe item “IMG_0346.JPG” can’t be copied because there isn’t enough free space. Card is 156 MB Photo is 1.56MB. Help please.

    Select the photo(s) in iPhoto and export to a desktop folder (file menu ==> export) - see this user tip for export options - then be sure the card is not locked and in the finder verify available space and if it is adaquate drag that folder to it
    LN

  • HT1338 I have added photos from iPhoto into Photo Stream and enabled my iCloud but I can't see any uploaded photos. Does this sound right?

    I have added photos from iPhoto into Photo Stream and enabled my iCloud but I can't see any uploaded photos. Does this sound right?

    Enable PhotoStream in iCloud first, then add the photos to PhotoStream in iCloud. Of course, you will need PhotoStream also enabled on your other devices also in order to view them.

  • I am using garage band for the first time.  I dragged and dropped a song from itunes into the program and I want to extend the length of the song by repeating the first 28 measures.  I can't figure it out.  Please help

    I am using garage band for the first time.  I dragged and dropped a song from itunes into the program and I want to extend the length of the song by repeating the first 28 measures.  I can't figure it out.  Please help.  I have spent several hours trying to figure it out on my own but have not been successful.  It seems like an easy task.  Can anyone help?

    dewin1or wrote:
    I want to extend the length of the song by repeating the first 28 measures.
    split the region at the 28th measure
    http://www.bulletsandbones.com/GB/GBFAQ.html#split
    (Let the page FULLY load. The link to your answer is at the top of your screen)
    then select only the first region and option-drag it to the end of the song

  • I plug my computer into my stereo and use the remote app on my iPhone to control it. How can I control my wires iPad with the remote app on my iphone when it is plugged into the stereo? they are different iTunes accounts.

    I plug my computer into my stereo and use the remote app on my iPhone to control it. How can I control my wires iPad with the remote app on my iphone when it is plugged into the stereo? they are different iTunes accounts.

    I think this is probably a sign that your network could be better than it is.
    Intermittent problems are often a result of interference. Interference can be caused by other networks in the neighbourhood or from household electrical items.
    You can download and install iStumbler (NetStumbler for windows users) to help you see which channels are used by neighbouring networks so that you can avoid them, but iStumbler will not see household items.
    Refer to your router manual for instructions on changing your wifi channel or adjusting your multicast rate.
    There are other types of problems that can affect networks, but this is by far the most common, hence worth mentioning first.

  • After moving from Canada to the US, getting a new iPhone 5C, and restoring my backup from iCloud, I can't update my apps. I get an error message that my account is not valid in the Canadian App store and I must change to the US store. How do I do that?

    After moving from Canada to the US, getting a new iPhone 5C, and restoring my backup from iCloud, I can't update my apps. I get an error message that my account is not valid in the Canadian App store and I must change to the US store. How do I do that?

    Change here:
    Settings > iTunes & App Stores > Apple ID: > View Apple ID > Country/Region.
    You must have a verified billing address & be located in the country whose store you are trying to use.

  • How do i resolve this....the program cant start because MSVC.dll is missing from your computer.ive uninstaled and reinstaled i tunes, still getting this message

    how do i resolve this....the program cant start because MSVC.dll is missing from your computer.ive uninstaled and reinstaled i tunes, still getting this message

    Click here and follow the instructions. You may need to completely remove and reinstall iTunes and all related components; this won't normally affect its library, but that should be backed up anyway.
    (99150)

  • HT204053 I cannot log into iCloud using my Apple username and password.  I keep getting an error message that states "CANNOT SIGN UP - The Apple ID is valid but is not an iCloud account."  How do I fix this?

    I cannot log into iCloud using my Apple username and password.  I keep getting an error message that states "CANNOT SIGN UP - The Apple ID is valid but is not an iCloud account."  How do I fix this?

    You are getting this message because you are attempting to create an iCloud account on a PC.  You can only create iCloud account on an iOS device (iPhone, iPad or iPod Touch) running iOS 5 or higher, or on a Mac running OS X Lion (10.7.2) or higher.  After creating your account on one of these devices you will then be able to sign into the account on your PC.

  • After saving a pdf in safari and trying to open I get an error

    After saving a pdf in safari and trying to open I get this error: There was an error opening this document. Acrobat cannot open this file because a task is still active in Acrobat. Please return to Acrobat and end the task before opening this file.

    Remove Acrobat and use Preview instead of the Adobe disease

  • HT4623 When I plug my new iphone 5 into my computer and click on itunes, I get a message that Itunes 10.7 is required on my phone. How do I update my iphone5 with itunes 10.7?

    When I plug my new iphone 5 into my computer and click on itunes, I get a message that Itunes 10.7 is required on my phone. How do I update my iphone5 with itunes 10.7?

    Thanks.  My computer is updated.  When I plug my iphone in, it does not pick up my iphone to sync and gives me the message indicated above.
    I cannot sync my new iphone with my computer.

Maybe you are looking for

  • Attendant line status at remote site

    we have a centralized 4.1.3 call manager with remote site using mpls. we set up the attendant application for the receptionist at the remote site and everything worked as expected. The next day, she no longer could see the line status. I've tried it

  • Itunes downloaded but won't open on Windows 8

    I just purchased a laptop with Windows 8 and Itunes downloaded fine but it won't open.  It says "Itunes has stopped working".  I have a Sony Vaio and my previous computer was a Sony Vaio so I know it should be working.  Any tips or advice on what to

  • IPhone say connect to iTunes, but neither iTunes or my computer recognize my iPhone now. What can I do?

    I tried updating my iPhone. Then at the end of the update, iTunes said it couldn't update my iOS because I didn't have the most up to date iTunes. Now my iPhone just says connect to iTunes, but neither iTunes or my computer recognize my iPhone now. W

  • Insert Picture/Hyperlink as Document Property

    Hi All, I have been able to insert most of the metadata into Word template as document properties but the Picture and Hyperlink column is not available. I also tried using INCLUDEPICTURE field like this: {INCLUDEPICTURE "http://<Site>/SiteCollectionI

  • ESB: Multimple instances support ?

    Hi all, I'm trying to invoke a Siebel webservice from a ESB service using multimple instances (like BPEL do, if possible) of my ESB Services . Here are my steps (quite simple): 1. Read data from a file (File Adapter Service), 3000+ records, 20 tab de