0

I have two params that are passed in a function which passed down to the SQL string. Variables can be null or has a value (int). If x is not null, use "this" column else use "that" column. I'm using SQL Server.

// Inside a function with two variables passed, x and y
$sql = "
  SELECT
    [...]
  FROM
    [...]
  WHERE
    [...]
    AND [...]
    -- This is the tricky part
    AND
    --- if $x is not null, use foo column else use bar column
    IF (x, R.column = 2, R.another_column = 3)
    [...]
";

Is this possible to select a column based on the value of the variable passed in?

1
  • I think you just looking for a case statement. Commented Jul 19, 2018 at 19:48

4 Answers 4

3
AND
(
   ($x is not null and R.column = 2) OR
   ($x is null and R.another_column = 3)
)
Sign up to request clarification or add additional context in comments.

Comments

2

Unless I'm misunderstanding, you just need logic, or a case statement would work.

$sql = "
  SELECT
    [...]
  FROM
    [...]
  WHERE
    [...]
  AND
    [...]
  -- This is the tricky part
  AND
    --- if $x is not null, use foo column else use bar column
    -- IF (x, R.column = 2, R.another_column = 3)
    (
    (X IS NULL AND R.column = 2)
    OR
    (X IS NOT NULL AND R.another_column = 3)
    )
";

Comments

0
AND
    --- if $x is not null, use foo column else use bar column
    case
      when x is NULL then R.another_column = 3 
      else R.column = 2 
    end

Comments

0
--in SQL Server...
DECLARE @x INT = 3;

SELECT *
FROM sys.schemas
WHERE (@x IS NULL AND schema_id = 2)
        OR (@x IS NOT NULL and schema_id = 3)
--optional depending on how much you execute this query, it may help
OPTION(RECOMPILE)

Comments

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.