SQL返回超过1个值的查询

时间:2019-05-29 20:20:51

标签: sql sql-server tsql

我在根据条件更新或插入列时遇到问题。我希望能够插入一个变量,如果该引用号在表中之前不存在,并且如果存在则应该更新。我的问题是@checklistscore返回的行多。当我选择@checklistscore时,它给出了相同的错误。我该如何解决

  SET XACT_ABORT ON; 
DECLARE @TRANSACTION VARCHAR(20) = 'EXAMPLE';
BEGIN TRAN @TRANSACTION
DECLARE @checklistscore INT;

SET @checklistscore = (SELECT 
      CASE 
        WHEN CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT) = 0 THEN NULL
        ELSE
        (
          CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  IN (2, 3, 50001, 50003, 50004, 50005, 50006, 50020, 50027, 50028) THEN EVALUATION ELSE NULL END) AS FLOAT)
            /
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT)
        ) * 100 

    END  FROM DB.D_CHECK_LIST   INNER JOIN DB.D_ENERGY_REFERENCE ON  D_CHECK_LIST.ID =D_ENERGY_REFERENCE.ID AND D_ENERGY_REFERENCE.REFERENCE = 19051
    GROUP BY D_CHECK_LIST.ID)

BEGIN

IF
    /* CHECKLIST TO UPDATE*/
    (EXISTS     
        (SELECT *
        FROM    DB.D_ENERGY_REFERENCE D_ENERGY_REFERENCE
                ,DB.D_CHECK_LIST D_CHECK_LIST
        WHERE   D_ENERGY_REFERENCE.ID = D_CHECK_LIST.ID
        AND     D_ENERGY_REFERENCE.REFERENCE = 19051


        )
)

BEGIN   
UPDATE DB.D_ENERGY_REFERENCE 
SET D_ENERGY_REFERENCE.VALUE_INTEGER =  @checklistscore 
FROM DB.D_ENERGY_REFERENCE
INNER JOIN DB.D_CHECK_LIST D_CHECK_LIST ON D_ENERGY_REFERENCE.ID = D_CHECK_LIST.ID
WHERE  D_ENERGY_REFERENCE.REFERENCE = 19051



END

ELSE 

BEGIN 

INSERT INTO DB.D_ENERGY_REFERENCE(ID, REFERENCE_NO, REFERENCE,VALUE_INTEGER)
(SELECT ID, 
                (SELECT  ISNULL(MAX(REFERENCE_NO), 0) + 1 FROM DB.D_ENERGY_REFERENCE),
                19051,  @checklistscore 

FROM DB.D_ENERGY_REFERENCE D_ENERGY_REFERENCE

GROUP BY D_ENERGY_REFERENCE.ID
)

END

1 个答案:

答案 0 :(得分:1)

我认为您需要做的是用临时表替换变量。临时表可以为每个ID存储1行。然后,脚本的后半部分将要使用ID作为联接条件与临时表联接,并以这种方式更新每一行。

(将我的评论重新发布为建议的答案。)