0

I need to rewrite a SQL scalar function which is called in power bi reports

how can I achieve the following in snowflake?

create function test (@input varchar(10)) returns varchar ( declare @text varchar(50) declare @cnt int select @cnt = max(key) from tbl;

if @input = 'table1' begin select @text = text from table1 --statements will be different based on input passed and is from tables end

if @input = 'table12' begin select @text = text from table12 where id = @cnt end

...

return @text )

Can you please share some examples where we can declare /set variables and also execute sql statements based on input parameter passed ?

Thanks, Jo

1 Answer 1

0

I think stored procedure works better in your case. I tried below examples and hope it is what are you after:

create or replace table test (a int);
insert into test values (1), (2);

create or replace table table1 (a varchar, id int);
insert into table1 values ('table1', 1);

create or replace table table2 (a varchar, id int);
insert into table2 values ('table2', 2);
  
CREATE OR REPLACE PROCEDURE my_proc(INPUT VARCHAR) 
RETURNS VARCHAR 
LANGUAGE JAVASCRIPT 
AS 
$$ 
    var stmt = snowflake.createStatement( {sqlText: "SELECT MAX(a) FROM test;"} ); 
    var resultSet = stmt.execute(); 
    resultSet.next(); 
    
    var id = resultSet.getColumnValue(1); 
    
    stmt = snowflake.createStatement( {sqlText: "SELECT a FROM " + INPUT + " WHERE id = " + id + ";"} ); 
    resultSet = stmt.execute(); 
    resultSet.next(); 
    
    return resultSet.getColumnValue(1);
$$ ; 

call my_proc('table2');
-- it returns "table2"

I have omitted any validations for simplicity.

Cheers

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.