Setting Big Query variables like mysql

前端 未结 5 543
鱼传尺愫
鱼传尺愫 2020-12-28 15:04

what is the bigquery equivalent to mysql variables like?

SET @fromdate = \'2014-01-01 00:00:00\',  -- dates for after 2013
@todate=\'2015-01-01 00:00:00\',

         


        
5条回答
  •  时光说笑
    2020-12-28 15:09

    Here is a solution using a user defined function. Declaring variables and calling them looks more like Mysql.

    You can call your variables by using function var("your variable name") this way:

    #standardSQL
    -- Set your variables here
    CREATE TEMP FUNCTION var(str STRING)
    RETURNS STRING
    LANGUAGE js AS """
      var result = {
        'fromdate': '2014-01-01 00:00:00',  // dates for after 2013
        'todate': '2015-01-01 00:00:00',
    
        'bfromdate': '2005-01-01 00:00:00', // dates for before 2013
        'btodate': '2005-01-01 00:00:00',
    
        'achfromdate': '2013-01-01 00:00:00', // dates for ACH without submit time in 2013
        'achtodate': '2013-01-01 00:00:00',
    
        'currency': 'USD',
    
        'minimumamount': '3.50',
    
        'default': 'undefined'
      };
      return result[str] || result['default'];
    """;
    -- Then use them by using the function var("your variable name")
    SELECT *
    FROM your_table
    WHERE date_column BETWEEN var("fromdate") AND var("todate")
    

    If your variable is not a string, set it as a string, call it with var and safe_cast it to your type:

    #standardSQL
    
    CREATE TEMP FUNCTION var(str STRING)
    RETURNS STRING
    LANGUAGE js AS """
      var result = {
        'minimumamount': '3.50',
        'default': 'undefined'
      };
      return result[str] || result['default'];
    """;
    
    SELECT *
    FROM your_table
    WHERE amount > safe_cast(var("minimumamount") AS FLOAT64)
    

提交回复
热议问题