How to declare and init variable in a dbt model in `.sql` file with big query adaptor? - dbt

I would like to declare and init a variable in a dbt model customer.sql file.
I used the keyword DECLARE to declare a variable like the BigQuery documentation suggests but I got
a Syntax error on DECLARE keyword.
Code:
DECLARE myDate VARCHAR DEFAULT '2021-01-01';
with order_bis as (
select
order_id
from
order
where
customer_date > myDate
)
select * from order_bis
Error:
Syntax error: Expected "(" or keyword SELECT or keyword WITH but got keyword DECLARE ...

It seems that using SQL variables does not work "yet" with dbt.
You can use Jinja variable if you want to use static values in multiple places, so that you can rely on Jinja logic.
{% set myVar = '2017-01-01' %}
...
where
customer_date > {{myVar}}
...

You can set them in the SQL header, e.g. as follows. Note that you can't safely use ref() or source() in the header.
-- Supply a SQL header:
{% call set_sql_header(config) %}
DECLARE myDate VARCHAR DEFAULT '2021-01-01';
{% endcall %}
with order_bis as (
select
order_id
from
order
where
customer_date > myDate
)
select * from order_bis

Related

Anything like template literals while writing a search query in SQL?

I am writing a stored procedure to get a particular value.
declare #num int
set #num = (SELECT Id
FROM [sometable]
WHERE Name like '%today%')
-- returns #num = 1
Select Value
FROM [anothertable]
where name like 'days1'
In the last line of the query I want to add "1" or any other number after 'days', depending on the variable #num.
How can I do it, sort of like how we use template literals in Javascript, using the ${} syntax but in SQL?
You can just use the first query as a sub-query of the second:
select [Value]
from anothertable
where [name] = Concat('days', (select Id from sometable where [Name] like '%today%'));

How to affect one selected Row to a local variable in T-SQL

I try to select one row from a table, and affect its value to a local declared variable I used the method below, but I got error.
Method:
DECLARE #A AS INT ;
SET #A=1;
WHILE #A<=10
BEGIN
DECLARE #R AS TABLE
SET #R = (SELECT * FROM Client c WHERE c.ID=#A)
SET #A=#A+1
END
Error I got :
Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'SET'.
So please how can I affect the subquery result to the R local variable ?
Table Variables cannot be assigned; you use DML to add data to a table variable. From docs
Assignment operation between table variables isn't supported.
table (Transact-SQL)
So something like:
DECLARE #R AS TABLE(ClientID int, Name nvarchar(200), ...)
INSERT INTO #R(ClientId, Name, ...)
SELECT ClientId, Name, ...
FROM Client c
WHERE c.ID=#A

Enum or constants in BigQuery?

Is it possible to create constants or enumerations in BigQuery in order to use them when making queries (selects)?
Example:
select *
from table
where column = __CONST_VALUE_TO_FILTER
When using BigQuery scripting, the DECLARE statement allows you to create constants as follows:
DECLARE variable_name[, ...] [variable_type] [DEFAULT expression];
According to that, in case you wanted to use as a filtering condition, you can use something similar to:
DECLARE x, y, z INT64 DEFAULT 0;
DECLARE var DEFAULT (SELECT item FROM other_table LIMIT 1);
select *
from table
where column = x;
Check the documentation on [1] to know more about the DECLARE and other StandardSQL statements.
[1] -
https://cloud.google.com/bigquery/docs/reference/standard-sql/scripting#declare
We frequently use the below syntax:
DECLARE var_timestamp_start DEFAULT '2020-01-01 00:00:00';
DECLARE var_timestamp_end DEFAULT '2020-01-01 00:00:00';
DECLARE var_countries DEFAULT [1,10,50];
select var_timestamp_start,var_timestamp_end,var_countries;
of course you are able to use them in Where filters as well

How to use a default in SELECT query?

I have created a default value like this:
create default [dbo].[MAX_DATE] as '31/12/9999 23:59:59'
Now I would like to return it from a sql query. I tried this:
SELECT
CASE date_field WHEN dbo.MAX_DATE THEN '' ELSE date_field END
FROM
myTable
However, I get the following error:
Server: Msg 107, Level 16, State 2, Line 2
The column prefix 'dbo' does not match with a table name or alias name used in the query.
Defaults are used by binding them to columns. The default value is applied by the server when a row is created and a column value isn't specified. (See: http://msdn.microsoft.com/en-us/library/ms173565.aspx)
Here are 3 options for you:
Option (1)
It looks like you're using a "named constant" for use in doing compares. In this case, you might want to go with a function, such as:
CREATE Function [dbo].[MAX_DATE] ()
Returns Datetime
as
BEGIN
Return '99991231 23:59:59'
END;
GO
select dbo.MAX_DATE()
Option (2)
Another option you might consider is having a table of named constants. It might have the columns: ID (autonumber), ValueName, numValue, strValue, dtValue, binValue. You would populate the ValueName and the appropriate column depending on what type of value you're storing in it.
Option (3)
To use a constant in just your current script, you can declare a value and set it's value and use it in the rest of your script. These variables are out of scope outside of their batch, so either when the script has finished running, or SQL encounters a GO statement. E.g.
DECLARE #MAX_VALUE as datetime
set #MAX_VALUE = '99991231 23:59:59'
select #MAX_VALUE

How to put column values in variables in SQL Server

I have a SQL Server table #SqlData with the following column splitdata.
splitdata
---------
BB10_1_X
4759
566549
I want to store these 3 column values into 3 different variables. Please help me as I am a beginner and I don't know how to do it..
You can declare variables like this:
DECLARE #Var AS VARCHAR(MAX)
And you can assign them using a select statement like this:
SELECT #Var=MyColumn
FROM MyTable
WHERE <My Condition>
There are plenty of resources on TSQL if you google it.
In your situation, if you're sure you will have exactly three rows, you can use three separate select statements:
DECLARE #Var1 AS VARCHAR(MAX), #Var2 AS VARCHAR(MAX), #Var3 AS VARCHAR(MAX)
SELECT #Var1=MyColumn
FROM MyTable
WHERE <My Condition That Returns First Row>
SELECT #Var2=MyColumn
FROM MyTable
WHERE <My Condition That Returns Second Row>
SELECT #Var3=MyColumn
FROM MyTable
WHERE <My Condition That Returns Third Row>