functionsnowflake-cloud-data-platform

Snowflake Function that returns string to be used in IN statement on Where Clause


I have created a Function in Snowflake that returns a string, its a list of numbers with a single quotes separating them.

CREATE OR REPLACE FUNCTION LOCATIONS()
RETURNS STRING
LANGUAGE SQL
AS
$$
  '''1','2','3','4','9'''
$$;

This returns the following: '1','2','3','4','9'

I want to use this in an in Statement like:

select *
from Table
where ID in ( select LOCATIONS() )

That table, the ID column is a number format, so I did the following:

select *
from Table
where to_varchar(ID) in ( select LOCATIONS() )

If I run this, it returns 0 results. If I copy the line above from the direct output of the function (select LOCATIONS() ) it returns results for me:

select *
from Table
where to_varchar(ID) in ( '1','2','3','4','9' )

What am I missing, I am not getting errors, and everything seems to be operating as it should.

I was expecting to get results from my query, but there is nothing.


Solution

  • try this

    CREATE OR REPLACE FUNCTION LOCATIONS()
    RETURNS TABLE (example_col varchar2(100))
    LANGUAGE SQL
    AS
    $$
         (with data as ( SELECT * FROM VALUES ('1'),('2'),('3'),('4'),('9')) select * from data)
    
    $$
    ; 
    
    select * from table(LOCATIONS())
    
    create table t1 (id char(20));
    insert into t1  (
        SELECT * FROM VALUES ('1'),('2'),('3'),('4'));
    select * from t1 where id in (select * from table(LOCATIONS()));
    

    enter image description here