create or replace trigger emp_trig
before insert or update of salary on emp
for each row
when `REGEXP_LIKE(:new.job_id, 'ac*','i')` -- Here
BEGIN
IF inserting then
:new.commission_pct := 0.20;
elsif (:old.commission_pct is null) then
:new.commission_pct := 0.1;
END IF;
END;
create or replace trigger emp_trig
before insert or update of salary on emp
for each row
when (REGEXP_LIKE(new.job_id, 'ac*','i'))
BEGIN
IF inserting then
:new.commission_pct := 0.20;
elsif (:old.commission_pct is null) then
:new.commission_pct := 0.1;
END IF;
END;
/
Hey. if you are trying to do a simple match then avoid using Regular
expression. Instead go with LIKE and your test condition. Below
snippet illustrates a simple example to suffice your requirement. Hope
it helps
CREATE OR REPLACE TRIGGER emp_trig before
INSERT OR
UPDATE OF sal ON emp FOR EACH row
WHEN (new.job LIKE '%TEST%')
DECLARE
BEGIN
IF inserting THEN
:new.comm := 0.20;
elsif (:old.comm IS NULL) THEN
:new.comm := 0.1;
END IF;
END;
Related
I am trying to create a Snowflake equivalent to the below T-SQL based adhoc query.
**T-SQL version**
Declare #i int = 0;
If(#i = 0)
PRINT '0';
Else
Begin
PRINT '1'
RETURN;
PRINT '2'
End
**Snowflake version**
Set i = 0;
If($i = 0)
Select '0';
Else
Begin
Select '1'
RETURN;
Select '2'
End
When I am running the Snowflake query from the Snowflake Web UI, I am getting an error as
SQL compilation error : syntax error line 1 at position 0 unexpected 'IF'
I have searched the snowflake documentation and did not find helpful documentation for:
If Else
Begin End
Return
Any help would be appreciated.
Thank you.
Snowflake does not support conditional T-SQL statements. It does support conditional expressions within a query.
For conditional statement execution, consider using Snowflake's stored procedures with embedded JavaScript if the use of conditional expressions is inadequate for your needs.
A very trivial example of a stored procedure, illustrating a conditional query execution upon call:
CREATE OR REPLACE PROCEDURE stored_proc_example(TEST_VALUE INTEGER)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
// Declaring SQL statement(s) to execute later
var command_1 = "SELECT 1";
var command_2 = "SELECT 2";
if (TEST_VALUE === 0) {
var stmt = snowflake.createStatement({ sqlText: command_1 });
var rs = stmt.execute();
// Omitted: Perform logic with 'rs' rows to prepare a return value
return '1';
} else {
var stmt = snowflake.createStatement({ sqlText: command_2 });
var rs = stmt.execute();
// Omitted: Perform logic with 'rs' rows to prepare a return value
return '2';
}
$$
;
Run as:
SET i=0;
CALL stored_proc_example($i);
SET i=1;
CALL stored_proc_example($i);
Snowflake Scripting introduced anonymous block and Branching constructs:
DECLARE
i INT DEFAULT 0;
BEGIN
IF (i = 0) THEN
RETURN 'zero';
ELSE
RETURN 'non-zero';
END IF;
END;
or:
BEGIN
LET i INT := 0;
IF (i = 0) THEN
RETURN 'zero';
ELSE
RETURN 'non-zero';
END IF;
END;
Further reading: Working with Variables
In Snowflake you can use CASE WHEN statements for this. Here's the documentation.
You can try with snowflake scripting and change your accordingly
set
stmt = $$
begin
let i := 1;
case when (i=0) then
return 0;
when (i=1 ) then
return '1 ';
else
return '2';
end ;
end;
$$;
execute immediate $stmt;
SELECT student_name 'Student Name',
CASE grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Good'
WHEN 'C' THEN 'Average'
WHEN 'D' THEN 'Poor'
WHEN 'F' THEN 'Fail'
ELSE 'N/A'
END 'Grade'
FROM student
-- Output
i'm new to sql and pl/sql. To practice I was giving an assignment to make a calculator. That part works. But they also want the possibility to type the calculation in the text field and then it needs to work. For example 4+4 (then the = button or enter on your keyboard) or 4+6-3=.
My calculator with buttons works, but not if I type a calculation in the text field. Can anyone help me with this?
This is the code I have in my total:
declare
l_operator varchar2(1) := :P3_OPERATOR;
l_value1 number := :P3_VALUE1;
l_value2 number := :P3_VALUE2;
l_result number := nvl(:P3_VALUE1,0);
begin
case l_operator
when '+' then
l_result := l_value1 + l_value2;
when '-' then
l_result := l_value1 - l_value2;
when '*' then
l_result := l_value1 * l_value2;
when '/' then
l_result := l_value1 / l_value2;
else
null;
end case;
:P3_OPERATOR := null;
:P3_VALUE2 := null;
:P3_VALUE1 := l_result;
:P3_NUMBERFIELD := l_result;
end;
with this for als extra for the +, -, * and \ .
:P12_OPERATOR := '*';
:P12_NUMBERFIELD := :P12_OPERATOR;
and this is the code for all my number buttons:
begin
if :P12_OPERATOR is null then
:P12_VALUE1 := :P12_VALUE1 || 4;
:P12_NUMBERFIELD := :P12_VALUE1;
elsif :P12_OPERATOR is not null then
:P12_VALUE2 := :P12_VALUE2 || 4;
:P12_NUMBERFIELD := :P12_VALUE2;
end if;
end;
This is not a typical way to use SQL or PL/SQL (or APEX which it looks like you are also using)!
You could evaluate any expression typed in with code like this:
begin
execute immediate 'select ' || :P3_NUMBERFIELD || ' from dual' into l_result;
exception
when others then
l_result := 'Invalid input';
end;
The exception part is to stop the calculator going wrong if the user types in nonsense like "hello world" instead of an arithmetic expression. The user would need to type in an expression like 4+4 without typing the equals sign, and then press a button to invoke the process to calculate the result.
I have the following code:
declare
l_input clob;
l_output clob;
function check_this_regex(
io_str in out clob
,o_found out clob
) return boolean
is
l_match clob;
begin
dbms_output.put_line('Matching against ->' || io_str || '<-');
l_match := regexp_substr(io_str, '"((y)*)"');
if l_match is null then
return false;
end if;
o_found := l_match;
return true;
end;
begin
l_input := to_clob('x');
dbms_output.put_line('l_input->' || l_input || '<-');
if (check_this_regex(l_input, l_output)) then
dbms_output.put_line('Found: ' || l_output);
else
dbms_output.put_line('Not found');
end if;
end;
Why does this output Found?
The problem should be checking a clob against NULL; editing your check this way
if l_match /* is null */ = empty_clob() then
gives :
l_input->x<-
Matching against ->x<-
Not found
regexp_substr for clob alwas returns not null value.Check example.
declare
v_clob clob;
v_in clob :='a';
v_str varchar2(10);
v_st_in varchar2(10) :='a';
begin
v_clob := regexp_substr(v_in,'xx');
if v_clob is null then
dbms_output.put_line('aaa');
end if;
v_str := regexp_substr(v_st_in,'xx');
if v_str is null then
dbms_output.put_line('aaa');
end if;
end;
I need to check a "substring of the first 6 characters" of an input string for a pure string.
declare
p_str varchar2(30) := 'ABCD1240';
l_result varchar2(20);
begin
if REGEXP_LIKE(substr(p_str,1,6), '[[:alpha:]]') then
dbms_output.put_line('It is a pure string');
else
dbms_output.put_line('It is an alphanumeric');
end if;
end;
/
I can see that the first 6 characters of the string ABCD1290 is alphanumeric as it contains 12.
But, the output that is printed says otherwise.
Am I doing something wrong with the "alpha" in regexp_like ?
I thought alpha was supposed to be pure characters and not numbers.
Here, ABCD1290 should give me: alphanumeric as output.
ABCDXY90 should be : pure string
Try this:
declare
l_res varchar2(100);
begin
for i in (select 'abcdef123' val from dual union
select '123abc123' from dual union
select '123456abc' from dual)
loop
if REGEXP_LIKE(i.val, '^\D{6}')
then
l_res := 'alpha';
else
l_res := 'numeric';
end if;
dbms_output.put_line(i.val || ' is ' || l_res);
end loop;
end;
123456abc is numeric
123abc123 is numeric
abcdef123 is alpha
I have a String stored in a table in the following key-value format: "Key1☺Value1☺Key2☺Value2☺KeyN☺ValueN☺".
Given a Key how can I extract the Value? Is regex the easiest way to handle this? I am new to PL/SQL as well as Regex.
In this case, I would use just a regular split and iterate through the resulting array.
public string GetValue(string keyValuePairedInput, string key, char separator)
{
var split = keyValuePairedInput.Split(separator);
if(split.Lenght % 2 == 1)
throw new KeyWithoutValueException();
for(int i = 0; i < split.Lenght; i += 2)
{
if(split[i] == key)
return split[i + 1];
}
throw new KeyNotFoundException();
}
(this was not compiled and is not pl/sql anyway, treat it as pseudocode ☺)
OK I hear your comment...
Making use of pl/sql functions, you might be able to use something like this:
select 'key' as keyValue,
(instr(keyValueStringField, keyValue) + length(keyValue) + 1) as valueIndex,
substr(keyValueStringField, valueIndex, instr(keyValueStringField, '\1', valueIndex) - valueIndex) as value
from Table
For this kind of string slicing and dicing in PL/SQL you will probably have to use regular expressions. Oracle has a number of regular expression functions you can use. The most commonly used one is REGEXP_LIKE which is very similar to the LIKE operator but does RegEx matching.
However you probably need to use REGEXP_INSTR to find the positions where the separators are then use the SUBSTR function to slice up the string at the matched positions. You could also consider using REGEXP_SUBSTR which does the RegEx matching and slicing in one step.
As an alternative to regular expressions...
Assuming you have an input such as this:
Key1,Value1|Key2,Value2|Key3,Value3
You could use some PL/SQL as shown below:
FUNCTION get_value_by_key
(
p_str VARCHAR2
, p_key VARCHAR2
, p_kvp_separator VARCHAR2
, p_kv_separator VARCHAR2
) RETURN VARCHAR2
AS
v_key VARCHAR2(32767);
v_value VARCHAR2(32767);
v_which NUMBER;
v_cur VARCHAR(1);
BEGIN
v_which := 0;
FOR i IN 1..length(p_str)
LOOP
v_cur := substr(p_str,i,1);
IF v_cur = p_kvp_separator
THEN
IF v_key = p_key
THEN
EXIT;
END IF;
v_key := '';
v_value := '';
v_which := 0;
ELSIF v_cur = p_kv_separator
THEN
v_which := 1;
ELSE
IF v_which = 0
THEN
v_key := v_key || v_cur;
ELSE
v_value := v_value || v_cur;
END IF;
END IF;
END LOOP;
IF v_key = p_key
THEN
RETURN v_value;
END IF;
raise_application_error(-20001, 'key not found!');
END;
To get the value for 'Key2' you could do this (assuming your function was in a package called test_pkg):
SELECT test_pkg.get_value_by_key('Key1,Value1|Key2,Value2|Key3,Value3','Key2','|',',') FROM dual