Consider the following SELECT query:
SELECT CourseID FROM Course
with data:
| CourseID |
|---|
| 112 |
| 101 |
| 125 |
| 173 |
| 145 |
| 152 |
| 160 |
We try to store the above result set into a variable. We try it like this:
DECLARE @a VARCHAR(MAX)
SELECT @a=CourseID FROM Course
Giving a PRINT @a returns just the last value: 160. So, obviously,
we cannot store 7 discrete values inside a scalar variable. We can use a table variable instead:
DECLARE @a TABLE (id int)
INSERT INTO @a
SELECT CourseID FROM Course
As you might have guessed giving a PRINT @a this time
returns a syntax error. The correct way to access @a
is to treat it like an ordinary table:
SELECT id FROM @a
No comments:
Post a Comment