My first table valued function and cursor

后端 未结 1 1568
名媛妹妹
名媛妹妹 2021-01-26 09:27

I have this query:

SELECT name, lastname
FROM contestant 
WHERE  name= \'John\'  AND lastname = \'Smith\'

I get several results from the query

相关标签:
1条回答
  • 2021-01-26 10:20

    OK as long as you understand that:

    1. The table designs are incorrect - you should have a contestant key in both tables.
    2. A join is the solution to this, not a cursor
    3. 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.

    0 讨论(0)
提交回复
热议问题