我有一个获取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参数没有传递给函数。
答案 0 :(得分:2)
你的考试(我在一读时错过了,对不起)足以让我很困惑。看来您的测试结果似乎不可能。
我唯一的建议是重新编码功能,看看会发生什么......
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
答案 1 :(得分:0)
我认为交叉申请是你想要的。