System.InvalidCastException error

Posted on 2005-05-12
Last Modified: 2010-03-19
(@CartID char(36), @gift smallint  OUTPUT)

SELECT @gift = SUM(Quantity)
FROM ShoppingCart
WHERE ShoppingCart.CartID = @CartID AND Gift = 1

Gift is a bit field. Quantity an int.
What I want to do is to total the Quantity field for every row where Gift = 1.
  Gift             Quantity
   1                   1
   0                   1
   1                   3           so in this case @gift would equal 4.

I tried the above but get an error:

Exception Details:
System.InvalidCastException: Cast from type 'DBNull' to type 'Short' is not valid = CType(command.Parameters("@gift").Value, Short)

But this line works in above: SELECT @gift = count(*)        . . . but I need to add the
Quantity to the count for every row where Gift = 1.
Question by:MikeMCSD
    LVL 28

    Accepted Solution

    Try this one:

    SELECT @gift = ISNULL(SUM(Quantity), 0)
    FROM ShoppingCart
    WHERE ShoppingCart.CartID = @CartID AND Gift = 1
    LVL 16

    Author Comment

    thank you . . that worked.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    6 Surprising Benefits of Threat Intelligence

    All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

    Suggested Solutions

    Performance is the key factor for any successful data integration project, knowing the type of transformation that you’re using is the first step on optimizing the SSIS flow performance, by utilizing the correct transformation or the design alternat…
    Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
    Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
    Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now