CREATE FUNCTION [dbo].[Test] (@ID INT, @VAL INT)
RETURNS @Return TABLE (ID INT, VAL INT)
AS
BEGIN
INSERT INTO @Return
SELECT @ID, @VAL
RETURN;
END
GO
DECLARE @T1 TABLE (ID INT IDENTITY(1,1), VAL INT)
DECLARE @T2 TABLE (ID INT, VAL INT)
INSERT INTO @T1
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
INSERT INTO @T2
SELECT 1,1
UNION
SELECT 2,4
UNION
SELECT 3,3
SELECT *
FROM @T1 T1
LEFT JOIN @T2 T2 ON T1.[ID] = T2.[ID]
LEFT JOIN [dbo].[Test] (1, COALESCE(T2.[VAL],T1.VAL)) T ON T1.ID = T.ID
GO
DROP FUNCTION [dbo].[Test]
GO
目标:
如果可用,将T2.Val传入fx的第二个参数,否则传递给T1.Val。无法更改外汇定义。
我似乎无法完成这项工作。我尝试过ISNULL,但这也不起作用。
答案 0 :(得分:3)
如果要调用表值函数,请使用APPLY
(在这种情况下为OUTER APPLY
,因为您使用的是LEFT JOIN
):
SELECT *
FROM @T1 T1 LEFT JOIN
@T2 T2
ON T1.[ID] = T2.[ID] OUTER APPLY
[dbo].[Test](1, COALESCE(T2.[VAL], T1.VAL) ) T;
如果您想要其他条件,请使用WHERE
子句:
SELECT *
FROM @T1 T1 LEFT JOIN
@T2 T2
ON T1.[ID] = T2.[ID] OUTER APPLY
[dbo].[Test](1, COALESCE(T2.[VAL], T1.VAL) ) T
WHERE t1.ID = T.ID;
但最后一个条件似乎很奇怪。为什么不直接将T1.ID
传递给函数?