I am trying to fetch each record of a table as a cursor and putting it into a custom table variable. I have kept the datatypes in the table variable same as the query result. But it doesn't seem to be working. Bellow is the code I am trying with.
Doesn't work:
DECLARE @MyCursor CURSOR;
DECLARE @r_field int;
DECLARE @r_DataSet TABLE
(
ID int,
Full_Name nVarChar(max)
);
BEGIN
SET @MyCursor = CURSOR FOR
select ID, custom_name as Full_Name from Students
where isDeleted = 0
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @r_DataSet
WHILE @@FETCH_STATUS = 0
BEGIN
--------------------------
--Some code
--------------------------
FETCH NEXT FROM @MyCursor
INTO @r_DataSet
END;
CLOSE @MyCursor ;
DEALLOCATE @MyCursor;
END;
This code is giving me this error "Must declare the scalar variable "@r_DataSet"."
Although it does work when I try this with only one field without table variable.
Works:
DECLARE @MyCursor CURSOR;
DECLARE @r_field int;
DECLARE @r_DataSet TABLE
(
ID int,
Full_Name nVarChar(max)
);
BEGIN
SET @MyCursor = CURSOR FOR
select ID from Students
where isDeleted = 0
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @r_field
WHILE @@FETCH_STATUS = 0
BEGIN
--------------------------
--Some code
--------------------------
FETCH NEXT FROM @MyCursor
INTO @r_field
END;
CLOSE @MyCursor ;
DEALLOCATE @MyCursor;
END;
I am not very experienced in T_SQL queries. Any help would be appreciated.
UPDATE:
As asked by others I will explain what I want to achieve here by giving you an example. Please let me know if I am using a wrong approach altogether.
Well, say I have these following tables-
questions table
( ID, TITLE, DESC )
TAGS table ( ID, NAME, DESC )
So,
For each question in questions table, I want to search for the matching tags (could be more than one) in tags table and insert the question-tag mapping data in another temporary table. I already have all the functions defined to check if a particular TAG is valid for a particular QUESTION or, not. The problem I am having is traversing the questions table record by record and searching the tags table based on the current record. Just to be clear there is no way to join these two tables as both these tables hold different types of data.
I hope this example clears the problem statement to you.