SQL存储过程:在游标中使用列名

时间:2013-10-16 06:40:52

标签: sql stored-procedures

想要读取一个表中的值并使用聚合函数的结果更新第二个表。给出的是这样的原始表:

lfnr    WertA    WertB    WertC
1      1       1       2
2      100     100     200
3      NULL    1       NULL
40     NULL    1       NULL
5      1       NULL    1
6      0       0       0
NULL   NULL    NULL    NULL

第二张表:

  CREATE TABLE table_2
(
CPOINT varchar(10),
RESULT float
);
INSERT INTO table_2 VALUES('WertA', 0)
INSERT INTO table_2 VALUES('WertB', 0)
INSERT INTO table_2 VALUES('WertC', 0)

现在我有一个更新table_2的存储过程:

CREATE PROCEDURE [dbo].[sp_result_top]
AS
BEGIN
    DECLARE @resultA float
    DECLARE @resultB float
    DECLARE @resultC float

    SET NOCOUNT ON;

        SET @resultA = 
        (SELECT AVG(CAST(s1 AS float)) FROM (SELECT TOP 3 WertA s1 
        FROM synta_rollmw WHERE WertA IS NOT NULL ORDER BY lfnr DESC)u);

        SET @resultB = 
        (SELECT AVG(CAST(s1 AS float)) FROM (SELECT TOP 3 WertB s1 
        FROM synta_rollmw WHERE WertB IS NOT NULL ORDER BY lfnr DESC)u);

        SET @resultC = 
        (SELECT AVG(CAST(s1 AS float)) FROM (SELECT TOP 3 WertC s1 
        FROM synta_rollmw WHERE WertC IS NOT NULL ORDER BY lfnr DESC)u);

        UPDATE table_2 SET RESULT=@resultA WHERE CPOINT='WertA'
        UPDATE table_2 SET RESULT=@resultB WHERE CPOINT='WertB'
        UPDATE table_2 SET RESULT=@resultC WHERE CPOINT='WertC'
END

这可行,但不是很好。我的方法是使用游标,从列cpoint读取值并在语句中使用它:

CREATE PROCEDURE [dbo].[sp_result_top_cursor]
AS
BEGIN
    DECLARE @result float
    -- Variable for Cursor
    DECLARE @cpoint CHAR(10)
    -- define Cursor
    DECLARE C1 CURSOR READ_ONLY FOR SELECT cpoint FROM table_2

    SET NOCOUNT ON;

    OPEN C1
    FETCH NEXT FROM C1 INTO @cpoint
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @result = 
        (SELECT AVG(CAST(s1 AS float)) FROM (SELECT TOP 3 @cpoint s1 
        FROM synta_rollmw WHERE @cpoint IS NOT NULL ORDER BY lfnr DESC)u)

        UPDATE table_2 SET RESULT=@result WHERE CPOINT=@cpoint
        FETCH NEXT FROM C1 INTO @cpoint
    END
    CLOSE C1
    DEALLOCATE C1
END

我可以创建过程但是尝试执行会在将varchar转换为int时出错。我认为我的错(再次)是使用变量@cpoint。这可以解决吗?谢谢!

0 个答案:

没有答案