Snowflake Table Function with Dynamic Columns

255 Views Asked by At

I'd like a table function that takes the fully qualified table name as an input and returns a 'select *' from that table excluding a specified range of columns. The specified columns are at the front of each table and not helpful for dev work.

This is the query that builds the SQL statement to be executed in the function:


  with cols as (

  SELECT LISTAGG(COLUMN_NAME || ',\n') WITHIN GROUP (ORDER BY COLUMN_NAME) as columns
  
  FROM INFORMATION_SCHEMA.COLUMNS

  WHERE 
    TABLE_CATALOG = (SPLIT(:table_name, '.')[0])
    AND TABLE_SCHEMA = (SPLIT(:table_name, '.')[1])
    AND TABLE_NAME = (SPLIT(:table_name, '.')[2])
    AND COLUMN_NAME NOT IN ('LIST_OF_COLS')
  )
  
  select 
    substr(columns,1,len(columns)-2) || '\n' as columns --remove trailing comma

  from cols
  ;

I have put this in a procedure and 'called' it but I want a table function so that I can use it in queries.

I realise that I could create a view for each table that does this but that's an ongoing overhead I'd prefer not burden myself with.

I know I could call the proc and use SELECT * from TABLE(RESULT_SCAN(LAST_QUERY_ID())); but that doesn't meet my requirements.

I'm also aware that output columns and datatypes must be specified in the function definition. I'm hoping there is a way!

0

There are 0 best solutions below