5

I have a table in SQL Server. The problem is how can I save the values of each column of a single row into separate variable in SQL Server 2012.

Something like:

SELECT Id, Name, School 
FROM tblSchool 
WHERE Id = 2

Then save the values of Id, Name, School into separate variables

3 Answers 3

5

If you want the values to be stored in separate variables (Your query returns only one matching row) You can do like following

DECLARE @ID INT
DECLARE @Name VARCHAR(100)
DECLARE @School VARCHAR(100)
SELECT TOP 1 @ID=Id,@Name=Name,@School=School FROM tblSchool WHERE Id=2

SQL Server also supports table type variables, for your case you can create a table type as following.

CREATE TYPE [dbo].[MyVairable] AS TABLE(
    Id                    INT NOT NULL,
    Name                   VARCHAR(100) NULL,
    School                 VARCHAR(100)
 )

Declare the variable as following.

 DECLARE @MyVariable [dbo].[MyVairable]

To select the rows into your variable.

INSERT INTO @MyVariable
SELECT Id,Name,School FROM tblSchool WHERE Id=2
Sign up to request clarification or add additional context in comments.

Comments

2

Simply Declare the variables and stored it using:

DECLARE @ID INT, @Name VARCHAR(50), @School VARCHAR(50)

SELECT @ID=Id,@Name=Name,@School=School FROM tblSchool WHERE Id=2

Comments

2
DECLARE @ID INT 
DECLARE @Name VARCHAR(50) 
DECLARE @School VARCHAR(50)

SELECT @ID=Id,@Name=Name,@School=School 
FROM tblSchool 
WHERE Id=2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.