问题
I have this query:
SELECT name, lastname
FROM contestant
WHERE name= 'John' AND lastname = 'Smith'
I get several results from the query above and I need to use them for the following query:
SELECT name, lastname,prize, city
FROM draw
WHERE name= name from table contestant AND lastname= name from table contestant
Now I’m building a table valued function with a cursor and a WHILE so I can have a table with the results.
Here’s my try, can you please help me complete it? it will be very helpful to me in order to understand this TSQL chapter. Thanks!
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
/* what do I have to input here */
DECLARE myCursor CURSOR FOR
SELECT name, lastname
FROM contestant
WHERE name= @name AND lastname = @lastname
OPEN myCursor
FETCH NEXT FROM myCursor INTO /* what goes here?*/
WHILE (@@FETCH_STATUS = 0)
BEGIN
-- and here?
FETCH NEXT FROM myCursor INTO /* what goes here?*/
END /*WHILE*/
CLOSE myCursor
DEALLOCATE myCursor
INSERT INTO @tmpTable (name, lastname,prize, city)
SELECT name, lastname,prize, city
FROM prize
WHERE name = @name AND lastname = @lastname
RETURN
END
回答1:
OK as long as you understand that:
- The table designs are incorrect - you should have a contestant key in both tables.
- A join is the solution to this, not a cursor
- What I am providing here is the worst possible way to solve this and what you need to learn from this is that you should never use this as a solution to this problem!
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.
来源:https://stackoverflow.com/questions/13400842/my-first-table-valued-function-and-cursor