If ... else statements

  • Hello,

    When I run the following query

    if (select T0.AppObjType

    from oinm T0

    inner join ibt1 T1 on T0.ItemCode = T1.ItemCode

    and T0.Warehouse = T1.WhsCode and T0.TransType = T1.BaseType

    and T0.CreatedBy = T1.BaseEntry and T0.DocLineNum = T1.BaseLinNum

    where T0.applobj = '202' AND AppObjAbs = '56'

    and T0.ItemCode = 'P100026') = 'P'

    BEGIN

    PRINT 'OUT'

    END

    I get the result correct, but when I combine it with the CTE, I get the error : -Incorrect syntax near the keyword 'IF'

    WITH BOM (Father,Code,Quantity) AS

    (

    SELECT ROOT.Father, ROOT.Code, ROOT.Quantity

    FROM dbo.ITT1 AS ROOT

    WHERE ROOT.Father = @itemcode

    UNION ALL

    SELECT CHILD.Father, CHILD.Code, CHILD.Quantity

    FROM dbo.ITT1 AS CHILD

    JOIN BOM ON CHILD.Father = BOM.Code

    )

    IF (select T0.AppObjType

    from oinm T0

    inner join ibt1 T1 on T0.ItemCode = T1.ItemCode

    and T0.Warehouse = T1.WhsCode and T0.TransType = T1.BaseType

    and T0.CreatedBy = T1.BaseEntry and T0.DocLineNum = T1.BaseLinNum

    where T0.applobj = '202' AND AppObjAbs = '56'

    and T0.ItemCode = 'P100026') = 'P'

    BEGIN

    PRINT 'OUT'

    END

    Where does the error come from, what wrong with the syntax ?

  • It simply wont allow you to do that as you are effectively splitting a single statement.

    I would suggest capturing the output of the query to a variable an testing that.



    Clear Sky SQL
    My Blog[/url]

  • Thanks,

    But how would I capture the out put in a variable because even this

    set @parent = (select T0.AppObjType

    from oinm T0

    inner join ibt1 T1 on T0.ItemCode = T1.ItemCode

    and T0.Warehouse = T1.WhsCode and T0.TransType = T1.BaseType

    and T0.CreatedBy = T1.BaseEntry and T0.DocLineNum = T1.BaseLinNum

    where T0.applobj = '202' AND AppObjAbs = '56'

    and T0.ItemCode = (select code from BOM))

    gives a similar error.

  • Here's a simple example

    declare @Result integer;

    with ctetest

    as(

    select 1 as Val

    )

    Select @Result = ctetest.val

    from ctetest

    Select @Result

    You may only use SELECT, INSERT, UPDATE or DELETE with a cte.



    Clear Sky SQL
    My Blog[/url]

  • Common table expression can be used in select /insert /update statement for one time only, as next statement of defination only.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply