0

I'm trying to add a conditional SELECT column in a query and I'm having trouble writing it out:

SELECT v.GLTypeID,
       v.something,
       v.somethignElse,
       CASE WHEN (SELECT TOP 1 Value FROM InterfaceParam WHERE InterfaceId = 0 AND Descr = 'gf') = 1 THEN a.CreditID ELSE NULL END AS CreditMemoID
FROM vGLDetails2 v
....
    LEFT OUTER JOIN AssociationFund f
        ON v.FundID = f.FundID
    LEFT JOIN dbo.APLedger a ON v.RelID = a.APLedgerID AND v.RelTypeID IN (39, 40)
....
ORDER BY v.Code;

The query above works, however if the CASE statement is still returning an additional column regardless of the result of the subquery. How can I remove it if the subquery doesn't return a row?

How can I do this?

6
  • AS can be applied to a column in the select list only, not to a partial expression. Commented Nov 7, 2022 at 17:07
  • Hey, just edited my question! Commented Nov 7, 2022 at 17:08
  • A case expression cannot sometimes result in a column and other times not, your question is not clear. You are however selecting one random row from your InterfaceParam table which can change on every execution, presumably you're ok with that? Commented Nov 7, 2022 at 17:12
  • 1
    You cannot. When the subquery returns no record SQL will (or should?) return NULL. This is because the number of columns returned by an SQL script is fixed (by the definition of the SQL statement). Commented Nov 7, 2022 at 17:12
  • @Stu Yes, that's fine. Looks like I cannot return a dynamic column then. Commented Nov 7, 2022 at 17:14

1 Answer 1

1

Change the location of AS. For example:

SELECT v.GLTypeID,
       v.something,
       v.somethignElse,
       CASE WHEN (
         SELECT TOP 1 Value 
         FROM InterfaceParam 
         WHERE InterfaceId = 0 AND Descr = 'creditMemo') = 1 
       THEN a.CreditID     -- AS is not valid here
       END AS CreditMemoID -- AS is valid here
FROM vGLDetails2 v
....
    LEFT OUTER JOIN AssociationFund f
        ON v.FundID = f.FundID
    LEFT JOIN dbo.APLedger a ON v.RelID = a.APLedgerID AND v.RelTypeID IN (39, 40)
....
ORDER BY v.Code;

Note: I removed ELSE NULL since this is the default behavior of CASE.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked! However, I'm trying to avoid adding the column if the subqery doesn't return a record now.
You cannot do that in a simple way. To produce a variable number of columns you can use Dynamic SQL, but that's a whole different ball game. It's simpler to detect the null in the UI and remove the column there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.