Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variable in WITH expression (SQL Server)?

Tags:

is there a way to define a variable inside a WITH expression? Something like:

;WITH SomeName AS ( 
    declare @somevar decimal
    set @somevar = ...
    SELECT ....)

Possible?

like image 650
grady Avatar asked Mar 09 '11 08:03

grady


People also ask

How do you DECLARE a variable in SQL Server?

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.

Can we DECLARE variables in CTE?

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.

How do I DECLARE a variable in a SQL table?

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.

What is @@ variable in SQL?

In SQL Server, symbol @@ is prefixed to global variables. The server maintains all the global variables.


2 Answers

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.

like image 74
AdaTheDev Avatar answered Nov 06 '22 07:11

AdaTheDev


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;
like image 33
Brian Goodwin Avatar answered Nov 06 '22 09:11

Brian Goodwin