为什么这个查询要求我在我已经拥有时声明表格?

时间:2010-10-26 14:15:15

标签: sql tsql

我的问题是这个sproc中的最后一个查询是说我需要声明@N,但我已经有了任何想法?

DECLARE @t TABLE
    (Smpinstanceid UNIQUEIDENTIFIER)

    INSERT INTO @t

    (Smpinstanceid)

    SELECT  t.SmpInstanceid
    FROM Tasks t
    WHERE t.Completed IS NOT NULL and t.SmpInstanceID is not null

DECLARE @N TABLE
(SMPinstanceid UNIQUEIDENTIFIER,[Count] INT)

INSERT INTO @N
(SMPinstanceid,[COUNT])

     SELECT Smpinstanceid,COUNT (Smpinstanceid) AS [Count]
                         FROM   @t
                         GROUP BY Smpinstanceid




            UPDATE Tasks
            SET    StepNum = @n.Count
            WHERE Tasks.SmpInstanceID = @n.smpinstanceid
END
GO

3 个答案:

答案 0 :(得分:2)

更新查询中没有对@n的引用。您需要使用子查询或“from”子句(如果这是sql server)进行更新

update tasks
  SET StepNum = (select Count from @n 
                     where Tasks.SmpInstanceID = @n.smpinstanceid ) 

update tasks
  set stepnum = n.count
  from tasks
    inner join @n as n
      on (Tasks.SmpInstanceID = n.smpinstanceid)

答案 1 :(得分:1)

您需要将表实际放在WHERE子句中的某个位置。

例如:

UPDATE T
SET StepNum = n.[Count]
FROM Tasks T
INNER JOIN @n n ON n.SmpInstanceId = T.SmpInstanceId

答案 2 :(得分:0)

你声明了@n,但它是一个表,并没有在Update子句中使用。您需要以某种方式将其添加到Update子句中,或者您需要将其更改为不是表。

UPDATE Tasks
SET    StepNum = @n.Count
FROM Tasks
JOIN @n on  Tasks.SmpInstanceID = @n.smpinstanceid