I have the function which gets ID and returns date from table if it exists or returns current date if isn't:
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;
The next queries return correct date from table:
select dbo.closedate(4170)
select dbo.closedate(id) from issues where id = 4170
And the next code update the record correctly (values from table):
DECLARE @d AS datetime
select @d = dbo.closedate(4170)
UPDATE issues SET created_on = @d WHERE issues.id = 4170
But I get current date in the field if I update the record:
UPDATE issues
SET created_on = dbo.CloseDate(id)
WHERE issues.id = 4170
It looks like the ID parameter doesn't pass to the function.