Explain Codes LogoExplain Codes Logo

How do I ignore ampersand characters in a SQL script running from SQL Plus?

sql
ampersand
set-define
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 4, 2024
TLDR

To ignore & or ampersand substitutions in SQL Plus, run the command SET DEFINE OFF.

SET DEFINE OFF; -- This command is essentially saying, "Hey, chill out with the ampersands!" -- SQL code goes here SET DEFINE ON; -- "Let's bring the party back on!" Now, ampersands are active again.

Ampersands in SQL Plus: Why so Special?

Usually, SQL Plus treats ampersands (&) as substitution variables promoting user interaction. It's a handy feature but, it can cause 'funny business' during automated script execution or when ampersands need to be taken literally.

Encasing Ampersands with Single Quotes

You can quote ampersands with single quotes to inhibit substitution when dealing with standalone strings.

SELECT 'Employee & Manager' AS Role FROM dual; -- because '&' in a role makes the role cooler!

Mastering 'SET DEFINE OFF'

Yet, if there are simply too many ampersands in your script to be handled individually, SET DEFINE OFF is your best friend. It instructs SQL Plus to lay off recognizing ampersands until the setting is toggled back on or the session is terminated.

The Art of Using CHR Function

Alternatively, ampersands can be included using the concatenation method with the CHR function (CHR(38) returns an ampersand):

SELECT 'Employee ' || CHR(38) || ' Manager' AS Role FROM dual; -- Do you know the magic number? It's 38!

Visualization

The 'SET DEFINE' command in SQL Plus working as the silencer in the city filled with noisy ampersands:

Before: 📞 SQL Plus 📞 ↔️ 🗣️'&'🗣️ ↔️ 📝 Script 🚫 After: 🛠️ SET DEFINE OFF 🛠️ ↔️ 📞 SQL Plus 📞 ↔️ 📝 Script 📢

With SET DEFINE OFF, SQL Plus becomes blissfully deaf to those distracting ampersand sounds.

Working with Advanced Ampersand Scenarios

For report generation scripts dealing with user-generated inputs like names, addresses etc., efficient handling of ampersands is crucial to avoid unexpected behavior.

Dealing with Configuration Nuances

Scripts run by automated tools or other interfaces can sometimes create issues with the SET DEFINE OFF command, leading you to rely on alternative methods or adjust the settings of the tool itself.

Wise Precautions & Best Practices

It's wiser to turn the DEFINE setting back ON after your script executes, especially when running multiple SQL files, to avoid unintended ampersand substitutions in the subsequent scripts:

SET DEFINE OFF; -- Tells SQL Plus, "Take a break, you've earned it!" -- The rest of your script goes here SET DEFINE ON; -- Says, "Missed you, buddy. Let's roll!" Turn define back on.

The SET DEFINE OFF command does not persist across different sessions. So, it's like a reset button, needs a fresh press every session.