在SQL(Hive)中声明变量

5

我已经在互联网上进行了深入的搜索,但我无法找到任何合适的答案。

在hive中,是否可以声明一个变量,比如说:

test = 1

如何在查询中更改此变量的值?

select
   case
      when field > 1 then test = test+1
      else test = 1
   end as test
from my table

1
https://dev59.com/jmcs5IYBdhLWcg3w8oXK - mohan111
您可以使用会话变量,例如: @test :=1 - lakhan_Ideavate
为什么会有“不行,做不到”的情况呢?原因有两个:(1)Hive编译查询以创建适当的执行计划,(2)这些参数是在客户端(fat CLI或thin Beeline客户端)上管理的,而不是在服务器端。可以将其想象成预处理器在最终文本编译之前进行文本替换。 - Samson Scharfrichter
1个回答

15

有可能。请查看以下代码以在Hive中创建一个变量。

hive> SET cust_id = 1234567890;

创建变量后,您可以在查询中像下面这样使用它。

hive> select * from cust_table where customer_id = '${hiveconf:cust_id}';

希望这可以帮助你。 现在你可以将其应用到你的场景中。


2
感谢您的回答!这个也可以: set ids = 1,2,3; select * from users where id in (${hiveconf:ids}); - Alex
此外,它可以用作列名而不是列中的值,例如:SET col_name = order_id; SELECT customer_id, ${hiveconf:col_name} from database.table_name; 假设表中有order_id列,则返回表的customer_id和order_id列。请注意,在分配变量时,赋值的值没有引号。 - Adiga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接