我花了很多时间阅读各种说明并尝试它们以使我的变量正常工作,但除了错误我什么也没得到。
这就是我正在尝试做的事情。顺便说一句,如果我能让它作为一个WITH子句在我的select语句的顶部工作,那就更好了,因为这个代码在整个查询中以不同的pcode组合重复使用。
--set a bind variable
VARIABLE pcode VARCHAR(3) --tried a bunch of various syntax with BEGIN/END/DECLARE/DEFINE...etc
--initiate the variable with
:pcode := (field1 || field2 || field 3) -- from my_table ? can't get syntax right here
--next I want to use the variable as follows
SELECT
--some field variables may be null so that only 1 or 2 characters are returned
DECODE (
pcode, 'A', amount_field * -1,
pcode, 'A1A', amount_field * -1,
pcode, 'A5', 0,
pcode, 'A6', 0,
pcode, 'B1', amount_field * -1,
pcode, 'B5', amount_field * 0,
pcode, 'B6', 0,
amount_field -- default
) as my_new_column -- set the value for each row in the table
FROM my_table
我真的很感激一些好的意见。请记住,这是 Oracle,因此并非一切都像常规 SQL 或 Postgres 中那样工作。
我尝试了很多组合 宣布 定义 开始结束 执行 / 选择进入 ...等等
我不知道我做错了什么。
您只想使用
pcode
作为第一个参数一次,如果 field1
、field2
和 field3
都是 my_table
的列,那么您不需要使用绑定变量:
SELECT DECODE (
field1 || field2 || field3,
'A', amount_field * -1,
'A1A', amount_field * -1,
'A5', 0,
'A6', 0,
'B1', amount_field * -1,
'B5', amount_field * 0,
'B6', 0,
amount_field -- default
) as my_new_column -- set the value for each row in the table
FROM my_table