选择在sql存储过程中插入更新

3htmauhk  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(354)

我试图从创建的过程中获取单个值,但显示错误为 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, 基本上我想返回 @statusReturn 但我怎么做不到,谁能告诉我如何做到这一点。

CREATE PROCEDURE [DBO].[uspGetJobStausAnyalyticaSpdDeltaRefresh]
( @Execution_Job_ID INT) 
AS 
  BEGIN
  SELECT TOP 3 
               ji.jobname, 
               jel.* 
    INTO       #tempjobstatus 
    FROM       jobexecutionlog jel  
    INNER JOIN jobinfo ji 
    ON         jel.jobid=ji.jobid 
    WHERE      jel.jobid IN (897,809,876) 
    AND        jel.jobexecutionlogid <= @Execution_Job_ID 
    ORDER BY   2 DESC 

    DECLARE @statusSPDRefresh  VARCHAR(30), 
      @statusAnalyticsRefresh  VARCHAR(30), 
      @statusJobExecutionLogId INT , 
      @statusReturn            INT
      SET @statusSPDRefresh = 
    ( 
           SELECT jobstatus 
           FROM   #tempjobstatus 
           WHERE  jobname ='Refresh')
           IF (@statusSPDRefresh = 'Failed') 
    BEGIN 
      SET @statusAnalyticsRefresh = 
      ( 
             SELECT jobstatus 
             FROM   #tempjobstatus 
             WHERE  jobname ='AnaRefresh') 
      IF (@statusAnalyticsRefresh = 'In Progress') 
      BEGIN 
        SET @statusJobExecutionLogId = 
        ( 
               SELECT jobexecutionlogid 
               FROM   #tempjobstatus 
               WHERE  jobname ='AnaRefresh') 
        UPDATE jobexecutionlog 
        SET    jobstatus = 'Failed' 
        WHERE  jobexecutionlogid = @statusJobExecutionLogId 
        SET    @statusReturn=1 
      END 
      ELSE SET @statusReturn =0
    END 
    ELSE  IF (@statusSPDRefresh = 'Completed') 
    BEGIN 
      SET @statusAnalyticsRefresh = 
      ( 
             SELECT jobstatus 
             FROM   #tempjobstatus 
             WHERE  jobname ='AnaRefresh') 
      IF (@statusAnalyticsRefresh = 'In Progress') 
      BEGIN 
        SET @statusJobExecutionLogId = 
        ( 
               SELECT jobexecutionlogid 
               FROM   #tempjobstatus 
               WHERE  jobname ='AnaRefresh') 
        UPDATE jobexecutionlog 
        SET    jobstatus = 'Completed' 
        WHERE  jobexecutionlogid = @statusJobExecutionLogId 
        SET    @statusReturn=1 
      END 
      ELSE SET @statusReturn =0
    END 
    ELSE 
   BEGIN 
    SET @statusReturn=0 
    END
    DROP TABLE #tempjobstatus
    END
9vw9lbht

9vw9lbht1#

您有许多这样的构造:

set @SomeVariable = (select ...)

但是如果select语句返回多个值,sql应该怎么做呢?例如:

create table t(i int)
go
insert t values (1), (2)
go
declare @i int;
set @i = (select i from t);

我有两个价值观 t 表1和表2。我们在这里做什么?我们不能把两个值都赋给一个变量。所以sql说“我不知道我应该在这里做什么”。
所以你才会出错。它意味着你至少有一个 set @variable = (select ...) 对您的 #tempjobstatus 表为正在使用的select语句返回多行。
您可以“强制”返回一行,例如使用 top 1 ,但这可能只会引入一个bug。因为如果不止一行,你想返回哪一行 top 1 ?
如果所有行都相同,则可以使用 distinct :

set @myvariable  = (select distinct somevalue from sometable)

但是如果有不止一个不同的值,那显然是没有用的。
我们不能给你“解决方案”。您需要考虑可能存在于您的特定系统中的数据,以及您试图用它做什么。但希望这个答案能帮助你理解这个问题。

相关问题