Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query, store result of SELECT in local variable

I create a query with some results reused. I search a way to put the result into a variable and use it.

A simple way to see what I want something looking like this - I want this:

DECLARE @result1 ?????  SET @result1 = SELECT a,b,c FROM table1 SELECT a AS val FROM @result1 UNION SELECT b AS val FROM @result1 UNION SELECT c AS val FROM @result1 

Not this :

 SELECT a AS val FROM (SELECT a,b,c FROM table1)  UNION  SELECT b AS val FROM (SELECT a,b,c FROM table1)  UNION  SELECT c AS val FROM (SELECT a,b,c FROM table1) 

It's not the result of this query that I'm concerned with, but instead:

  1. to stop selecting the result so many times - in my sample, I reselected the table 3 times

  2. the query of @result1 is usually so much more complex. So, with a variable, the code will be cleaner.

Maybe I want to much - or there's a type of local variable. Or using the type table and set data inside.

What do you suggest me?

Thank you

like image 651
forX Avatar asked Apr 27 '12 18:04

forX


People also ask

Can we store a query in a variable?

Yup, this is possible of course.

How do you assign a value to a variable in SQL stored procedure?

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.


1 Answers

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)  INSERT INTO @result1 SELECT a, b, c FROM table1  SELECT a AS val FROM @result1 UNION SELECT b AS val FROM @result1 UNION SELECT c AS val FROM @result1 

This should be fine for what you need.

like image 105
Vince Pergolizzi Avatar answered Oct 10 '22 10:10

Vince Pergolizzi