is there a way to define a variable inside a WITH expression? Something like:
;WITH SomeName AS (
declare @somevar decimal
set @somevar = ...
SELECT ....)
Possible?
Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.
The SELECT statement for CTE_query_definition must meet the same requirements as for creating a view, except a CTE cannot define another CTE. A CTE should return rows. I don't think you can use it for assigning variables at all.
To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server.
In SQL Server, symbol @@ is prefixed to global variables. The server maintains all the global variables.
No, you would need to declare / set it outside of the CTE
DECLARE @somevar DECIMAL
;WITH SomeName AS (SELECT....)
SELECT @somevar = ...
FROM SomeName
Per MSDN:
CTE_query_definition
Specifies a SELECT statement whose result set populates the common table expression. The SELECT statement for CTE_query_definition must meet the same requirements as for creating a view, except a CTE cannot define another CTE.
I've had to use the following approach a few times as a work-around (for example using R-Server in t-sql as the input_data_1 expression; see https://docs.microsoft.com/en-us/sql/advanced-analytics/tutorials/quickstart-r-inputs-and-outputs?view=sql-server-2017). The following illustrates the example:
WITH ctename (varname) as (
SELECT MAX(somevar) FROM sometable
)
SELECT *
FROM someothertable a
JOIN ctename b on 1=1
WHERE a.col1 > b.varname;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With