我知道错误很明显,但我似乎无法找到为什么它会返回超过1的结果,我该怎么办?
我想知道当前一年的项目开始日期之间还剩多少周。所以我用datediff计算startdate和enddate之间的周差。确定这两个日期都在今年。我一直在检查其他许多问题,但无法找到类似的问题,因为只有返回1个值。提前谢谢。
CREATE FUNCTION [dbo].[fWksInCurrentYr] (@projectId int)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @sDateCY DateTime
DECLARE @eDateCY DateTime
DECLARE @startCY DateTime
DECLARE @endCY DateTime
DECLARE @returnvalue int
SET @startCY = DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
SET @endCY = DATEADD(yy, DATEDIFF(yy,0,getdate()) + 1, -1)
SET @sDateCY = (SELECT ServiceRequest.StartDate FROM dbo.ServiceRequest WHERE dbo.ServiceRequest.[Project_ID] = @projectId)
SET @eDateCY = (SELECT ServiceRequest.EndDate FROM dbo.ServiceRequest WHERE dbo.ServiceRequest.[Project_ID] = @projectId)
SET @sDateCY = CASE
WHEN @sDateCY < @startCY THEN @startCY
ELSE @sDateCY
END
SET @eDateCY = CASE
WHEN @eDateCY > @endCY THEN @endCY
ELSE @eDateCY
END
SELECT TOP 1 @returnvalue=IsNull(datediff(ww,@sDateCY,@eDateCY),0)
RETURN @returnvalue
END
如果我然后使用此查询,我会收到错误: SELECT [dbo]。[fWksInCurrentYr]([Project]。[ID]) 来自[项目]
答案 0 :(得分:1)
更改以下内容:
SET @sDateCY = (SELECT TOP 1 ServiceRequest.StartDate FROM dbo.ServiceRequest WHERE dbo.ServiceRequest.[Project_ID] = @projectId)
SET @eDateCY = (SELECT TOP 1 ServiceRequest.EndDate FROM dbo.ServiceRequest WHERE dbo.ServiceRequest.[Project_ID] = @projectId)
或者你可以更优雅地写出这样的东西......
SELECT TOP 1 @sDateCY = ServiceRequest.StartDate
,@eDateCY = ServiceRequest.EndDate
FROM dbo.ServiceRequest
WHERE dbo.ServiceRequest.[Project_ID] = @projectId
注意的
您无法从查询中返回数据并同时为变量赋值,但您可以同时为多个变量赋值。就像我在建议的解决方案中所做的那样。
答案 1 :(得分:0)
你写过
SET @sDateCY = (SELECT ServiceRequest.StartDate FROM dbo.ServiceRequest
WHERE dbo.ServiceRequest.[Project_ID] = @projectId)
而不是这个,试试这个
SELECT @sDateCY = ServiceRequest.StartDate FROM dbo.ServiceRequest
WHERE dbo.ServiceRequest.[Project_ID] = @projectId
@eDateCY 变量相同。
可以解决您的问题,但不确定它是否有效。