You should use hash (#) tables, That you actually looking for because variables value will remain till that execution only.
e.g. -
declare @TEMP table (ID int, Name varchar(max))
insert into @temp SELECT ID, Name FROM Table
When above two and below two statements execute separately.
SELECT * FROM @TEMP
WHERE @TEMP.ID = 1
The error will show because the value of variable lost when you execute the batch of query second time.
It definitely gives o/p when you run an entire block of code.
The hash table is the best possible option for storing and retrieving the temporary value. It last long till the parent session is alive.
SELECT * FROM @TEMP T WHERE T.ID = 1
– Altagraciaaltaic