I have this query:
SELECT name, lastname
FROM contestant
WHERE name= \'John\' AND lastname = \'Smith\'
I get several results from the query
OK as long as you understand that:
But in answer to your question how do I use a cursor, here is some untested code that hopefully gives you the concept.
CREATE FUNCTION [dbo].[myFunction]
(
@name varchar (44),
@lastname varchar (44)
)
RETURNS
@tmpTable TABLE
(
name char(44),
lastname char(44),
prize varchar(44),
city char(44)
)
AS
BEGIN
DECLARE @c_name varchar (44)
DECLARE @c_lastname varchar (44)
DECLARE myCursor CURSOR FOR
SELECT name, lastname
FROM contestant
WHERE name= @name AND lastname = @lastname
OPEN myCursor
FETCH NEXT FROM myCursor INTO @c_name, @c_lastname
WHILE (@@FETCH_STATUS = 0)
BEGIN
-- we've found a row. Name look for the matching row in prize
INSERT INTO @tmpTable (name, lastname,prize, city)
SELECT name, lastname,prize, city
FROM prize
WHERE name = @c_name AND lastname = @c_lastname
FETCH NEXT FROM myCursor INTO @c_name, @c_lastname
END /*WHILE*/
CLOSE myCursor
DEALLOCATE myCursor
RETURN
END
and as a comparison, here is the proper solution:
SELECT draw.name, draw.lastname, draw.prize, draw.city
FROM
draw
INNER JOIN
contestant
ON draw.name = contestant.name
AND draw.lastname = contestant.lastname
WHERE contestant.name= 'John'
AND contestant.lastname = 'Smith'
Its smaller, simpler and faster.