sql – 由函数更新字段

我有这个函数获取ID并从表中返回日期(如果存在)或返回当前日期(如果不存在):

CREATE FUNCTION [dbo].[CLOSEDATE] (@ID int)
RETURNS datetime
AS
  BEGIN
     DECLARE @closed int;
     DECLARE @result datetime;

     SELECT @result = created_on from dbo.statuses_history
            WHERE journalized_id = @ID and new_status = 'Закрыто';

     IF @result IS NULL    
        SELECT @result = GETDATE()     

     RETURN (DATEADD(dd, 0, DATEDIFF(dd, 0, @result)))
  END;

下一个查询从表中返回正确的日期:

select dbo.closedate(4170)
select dbo.closedate(id) from issues where id = 4170

并且下一个代码正确更新记录(表中的值):

DECLARE @d AS datetime
select @d = dbo.closedate(4170)
UPDATE issues SET created_on = @d  WHERE issues.id = 4170

但是如果我更新记录,我会在该字段中获得当前日期:

UPDATE issues
SET created_on = dbo.CloseDate(id)
WHERE issues.id = 4170

看起来ID参数没有传递给函数.

最佳答案 你的考试(我在一读时错过了,对不起)足以让我很困惑.似乎您的测试结果不可能.

我唯一的建议是重新编码功能,看看会发生什么……

CREATE FUNCTION [dbo].[CLOSEDATE] (@ID int)
RETURNS TABLE
AS
RETURN
  SELECT
    (DATEADD(dd, 0, DATEDIFF(dd, 0, ISNULL(MAX(created_on), GetDate())))) AS close_date
  FROM
    dbo.statuses_history
  WHERE
    journalized_id = @ID
    AND new_status = 'Закрыто'

然后…

UPDATE
  issues
SET
  created_on = fn.close_date
FROM
  issues
CROSS APPLY
  dbo.CLOSEDATE(id) AS fn
WHERE
  issues.id = 4170
点赞