0

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

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 的使用。这可以解决吗?谢谢!

4

0 回答 0