简体   繁体   中英

Oracle: How to reference an alias with a space from a subquery in a comparison operation

Is there a way to reference an alias that has a space in it in an Oracle SQL Query? I haven't found it anywhere yet. Normally I don't use spaces for naming database elements, so this is new ground for me.

Here's an example query:

SELECT  t.id AS "Ticket ID",
(SELECT w.workgroup_title FROM workgroups w
WHERE w.operator_id = t.operator_id AND ROWNUM < 2) AS "Workgroup Title"
FROM tickets t

How would I use "Ticket ID" or "Workgroup Title" in a future comparison operation? For example:

"Ticket ID" == 9 or "Workgroup Title" == 'Workgroup #1'

I'm guessing there's an easy way to do this, just haven't found it yet.

Thanks!

PS This is for a legacy piece that was handed to me. The aliases in the SQL tie dynamically into other various code, and all have spaces. As a result, removing the spaces isn't a simple matter and I currently haven't been budgeted the time for it. Otherwise, that's what I'd do.

Edit for Clarification
Using the example above, how would I do something like this where "Workgroup Title" always refers to the alias:

SELECT  t.id AS "Ticket ID",
(SELECT w.workgroup_title FROM workgroups w
WHERE w.operator_id = t.operator_id AND ROWNUM < 2) AS "Workgroup Title",
(SELECT s.support_tier_id FROM support_tiers s
WHERE s.workgroup_title == "Workgroup Title") AS "Support Tier ID"
FROM tickets t

Yes, you can do this, but you have to enclose those names in double quotes:

-- SQL Example
SELECT "Just one" FROM (
  SELECT 1 AS "Just one" FROM dual
);

Output:

Just one
----------
         1
-- PL/SQL Example
BEGIN
  FOR v_rec IN (SELECT 1 AS "Just one" FROM dual)
  LOOP
    dbms_output.put_line(v_rec."Just one");
  END LOOP;
END;
/

Output:

1

And a little curiosity:

BEGIN
  FOR v_rec IN (SELECT COUNT(1) * 10 FROM dual)
  LOOP
    dbms_output.put_line(v_rec."COUNT(1)*10");
  END LOOP;
END;

This works.. and prints:

10

Edit

You can reference the aliased column elsewhere in your query, for example:

SELECT 'It is just one' FROM (
  SELECT "Just one" FROM (
    SELECT 1 AS "Just one" FROM dual
  ) t
WHERE t."Just one" = 1 -- prefixing with t. is not necessary in this particular example
);

Output:

It is just one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM