none
Inline IF RRS feed

  • Question

  • Hi,

    I would like to convert the following to an Inline IF statement.

    decimal TOTAL;

    if (columns[24] != "" || columns[24] != "|~||~|")

    {
    TOTAL = Convert.ToDecimal(columns[24].Replace("|~|", ""));
    }


    I've had a go myself  the first attempt gave the following error,

    columns[24] != "" || columns[24] != "|~||~|" ? TOTAL = Convert.ToDecimal(columns[24].Replace("|~|", "")):null;

    Only assignment, call, increment, decrement, and new object expressions can be used as a statement.

    The second attempt gave me the following error,

    TOTAL = columns[24] != "" || columns[24] != "|~||~|" ?  Convert.ToDecimal(columns[24].Replace("|~|", "")):null;

    Type of conditional expression cannot be determined because there is no implicit conversion between 'decimal' and '<null>'

    *** It is important that I return null if columns[24] is "" or |~||~| ***

    Thanks,

    Ben




    Mr Shaw... One day I might know a thing or two about SQL Server!

    Tuesday, November 15, 2016 12:07 PM

Answers

  • In that case the second example is what you want, so:

    DataBuffer.TOTAL = (columns[24] != "" || columns[24] != "|~||~|")
                    ? Convert.ToDecimal(columns[24].Replace("|~|", ""))
                    : 0M;

    • Marked as answer by Mr Shaw Tuesday, November 15, 2016 1:25 PM
    Tuesday, November 15, 2016 1:04 PM

All replies

  • I believe you are looking for The conditional operator

    The problem I see is that you are trying to set a Decimal as a null, if it's a nullable decimal though it can work.

                decimal? TOTAL = (columns[24] != "" || columns[24] != "|~||~|")
                    ? Convert.ToDecimal(columns[24].Replace("|~|", ""))
                    : (decimal?) null;

    You could also change this to return 0 instead of null if you don't want "TOTAL" to be nullable:

                decimal TOTAL = (columns[24] != "" || columns[24] != "|~||~|")
                    ? Convert.ToDecimal(columns[24].Replace("|~|", ""))
                    : 0M;

    Tuesday, November 15, 2016 12:18 PM
  • Thanks for the help.

    I think I should have posted the following script.  

    if (columns[24] != "" || columns[24] != "|~||~|")

                    {

                        DataBuffer.TOTAL =

    Convert.ToDecimal(columns[24].Replace("|~|", ""));

                    }

    I am working with SQL SSIS and the DataBuffer is an output buffer.

    DataBuffer.Total is a decimal.

    Thanks,

    Ben


    Mr Shaw... One day I might know a thing or two about SQL Server!

    Tuesday, November 15, 2016 12:29 PM
  • In that case the second example is what you want, so:

    DataBuffer.TOTAL = (columns[24] != "" || columns[24] != "|~||~|")
                    ? Convert.ToDecimal(columns[24].Replace("|~|", ""))
                    : 0M;

    • Marked as answer by Mr Shaw Tuesday, November 15, 2016 1:25 PM
    Tuesday, November 15, 2016 1:04 PM