SQL将计数值添加到另一个表

时间:2017-05-09 18:27:21

标签: sql sql-server-2008

嘿,伙计们,所以我得到了数值。 我想将它作为一个存储过程运行,以使用从计数中得到的值来更新另一个表。

SELECT COUNT(*) as counted 
FROM [DB]
WHERE Date_Timestamp >= DATEADD(HOUR,6,CONVERT(VARCHAR(10), GETDATE(),110))
AND Date_Timestamp <= DATEADD(HOUR,18,CONVERT(VARCHAR(10), GETDATE()+1,110))
and trigger_loc = 'x'

2 个答案:

答案 0 :(得分:0)

不需要存储过程。我会使用CTE:

WITH newdata as (
      SELECT COUNT(*) as counted 
      FROM [DB]
      WHERE Date_Timestamp >= DATEADD(HOUR, 6, CAST(GETDATE() as DATE)) AND            
            Date_Timestamp <= DATEADD(HOUR, 18 + 24, CAST(GETDATE() as DATE)) AND
            trigger_loc = 'x'
    )
update toupdate
    set col = counted
    from t toupdate join
         newdata
         on toupdate.?? = newdata.??;

这也简化了日期算术,因此不需要转换为字符串。

目前还不清楚要更新哪一行。这假设某个键上有join

答案 1 :(得分:0)

如果你想把它变成一个存储过程,你可以这样做:

CREATE PROCEDURE dbo.UpdateTableWithCountedValue AS
BEGIN
    UPDATE [Table You Want To Update]
    SET [column you want to update] = (SELECT COUNT(*) as counted 
  FROM [DB]
  WHERE Date_Timestamp >= DATEADD(HOUR, 6, CAST(GETDATE() as DATE)) AND            
        Date_Timestamp <= DATEADD(HOUR, 18 + 24, CAST(GETDATE() as DATE)) AND
        trigger_loc = 'x')
    WHERE [ConditionForRowsThatShouldBeUpdated]
END

然后您可以随时调用存储过程:

exec dbo.UpdateTableWithCountedValue