1

I can use variables for query filtering conditions. E.g.,

set mytime = '2021-12-12 09:00:00';

select col1
from db1.schema.table1
where event_time > $mytime

However, if I use the same way to replace the db1 with a variable, it will not work. I.e.,

set mytime = '2021-12-12 09:00:00';
set db_name = 'db1';

select col1
from $db_name.schema.table1
where event_time > $mytime
2
  • You might not be able to use it directly, but you can do use database identifier($db_name) and then select query excluding dbname qualifier, like select colname from schema_name.table; Commented Apr 16, 2022 at 0:53
  • See the session variable section of docs.snowflake.com/en/sql-reference/… Commented Apr 16, 2022 at 2:01

1 Answer 1

3

So if your variable has a fully qualified name db/schema/table name and you use the IDENTIFIER function can help.

create table test.test.db1(id number);

set db_name = 'test.test.db1';

insert into test.test.db1 values (1),(2),(3);

then this works:

select id
from identifier ($db_name);
ID
1
2
3

but composing the string on the fly does not presently work:

select id
from identifier ($just_db_name||'.test.db1');

but you can two step this:

set fqn_db_name = $just_db_name||'.test.db1';

select id
from identifier ($fqn_db_name);
ID
1
2
3

Snowflake Scripting:

Using snowflake scripting, it can be done as a single "statement", like so:

begin
    let fqn text := $just_db_name || '.test.db1';
    let res resultset := (select id from identifier(:fqn));
    return table(res);
end; 
ID
1
2
3
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.