gpt4 book ai didi

SQL Server : cannot access temporary tables

转载 作者:行者123 更新时间:2023-12-02 09:57:43 27 4
gpt4 key购买 nike

如何从此查询创建表值函数?

我需要计算开始和结束作业时间之间的时间作为结果HH:MM

当我在 SQL 中运行该查询时,该查询有效:

DECLARE @USERID int;
SET @USERID = 10

DECLARE @JOBStartDATE DATETIME;
SET @JOBStartDATE = (SELECT StartJOBHoursDATE FROM JOBs WHERE ID=@USERID)


DECLARE @StartTime DATETIME;
DECLARE @JOBDateTime DATETIME;
DECLARE @JOBEvent nvarchar(50);
DECLARE @totalTime int;
SET @totalTime = 0;

SELECT ROW_NUMBER() OVER(ORDER BY JOBID) AS ROWNUM, JOBDateTime,JOBEvent INTO #TEMP FROM JOBsActivityData where JOBID = @USERID and JOBDateTime >= @JOBStartDATE
DECLARE @MaxRownum INT
SET @MaxRownum = (SELECT MAX(RowNum) FROM #TEMP)
DECLARE @Iter INT
SET @Iter = (SELECT MIN(RowNum) FROM #TEMP)

WHILE @Iter <= @MaxRownum
BEGIN
SET @JOBDateTime =(SELECT JOBDateTime FROM #TEMP WHERE RowNum = @Iter)
SET @JOBEvent =(SELECT JOBEvent FROM #TEMP WHERE RowNum = @Iter)
IF(@JOBEvent = 'START')
BEGIN
SET @StartTime =(SELECT JOBDateTime FROM #TEMP WHERE RowNum = @Iter)
END
IF(@JOBEvent = 'END' AND @StartTime IS NOT NULL)
BEGIN
SET @totalTime = @totalTime + (SELECT DATEDIFF(minute,@StartTime,@JOBDateTime))
SET @StartTime = NULL;
END

SET @Iter = @Iter + 1
END

DROP TABLE #TEMP

SELECT CAST((@totalTime / 60) AS VARCHAR(8)) + ':' +
CAST((@totalTime % 60) AS VARCHAR(2)) AS JOBHours

当我尝试创建时出现此错误

Cannot access temporary tables from within a function.

最佳答案

服务器不允许修改函数中的任何表。请改用表变量。

declare @temp table (RowNum int, JOBDateTime DateTime, JOBEvent int)

insert into @temp
SELECT ROW_NUMBER() OVER(ORDER BY JOBID) AS ROWNUM,
JOBDateTime,
JOBEvent
FROM JOBsActivityData
where JOBID = @USERID and JOBDateTime >= @JOBStartDATE
...

使用表变量时,不需要删除它们。

关于SQL Server : cannot access temporary tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14545432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com