我的第一个表值得函数和光标

时间:2012-11-15 15:35:54

标签: sql-server tsql function cursor while-loop

我有这个问题:

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

我从上面的查询中得到了几个结果,我需要将它们用于以下查询:

SELECT  name, lastname,prize, city 
FROM draw
WHERE  name= name from table contestant  AND lastname= name from table contestant  

现在我正在用光标和WHILE构建一个表值函数,所以我可以得到一个包含结果的表。

这是我的尝试,你能帮我完成吗?为了理解这个TSQL章节,对我来说非常有帮助。谢谢!

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 个答案:

答案 0 :(得分:3)

好的,只要你明白:

  1. 表格设计不正确 - 您应该在两个表格中都有参赛者密钥。
  2. 联接是解决方案,而不是游标
  3. 我在这里提供的是解决这个问题的最糟糕的方法,你需要从中学到的是你永远不应该用它来解决这个问题!
  4. 但是在回答你的问题我如何使用游标时,这里有一些未经测试的代码,希望能为你提供这个概念。

    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
    

    作为比较,这是正确的解决方案:

    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'
    

    它更小,更简单,更快。