Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store the select column in a variable?

How do I store the select column in a variable?

I tried this, but it throws me an error "Incorrect syntax":

declare @EmpId int
SELECT  dbo.Employee.Id as @EmpId FROM  dbo.Employee
like image 874
Nick Kahn Avatar asked Feb 25 '11 17:02

Nick Kahn


People also ask

How will you store select query result in variable SQL?

This provides a way to save a result returned from one query, then refer to it later in other queries. The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving.

Can we store a query in a variable?

Yup, this is possible of course. Here are several examples.


3 Answers

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

like image 167
Jimmy Avatar answered Oct 12 '22 11:10

Jimmy


Assuming such a query would return a single row, you could use either

select @EmpId = Id from dbo.Employee

Or

set @EmpId = (select Id from dbo.Employee)
like image 20
Joe Stefanelli Avatar answered Oct 12 '22 11:10

Joe Stefanelli


This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

like image 24
Neil Knight Avatar answered Oct 12 '22 12:10

Neil Knight