目标:
我想在我的函数中有一个参数,以允许用户输入值列表。理想情况下,最简单的解决方案...注意:我没有在dbs中创建表的权限。
情况:
CREATE FUNCTION dbo.fnExample
(
@StartDate AS Date -- Parameter 1
@ParameterArray AS ... -- This would be the parameter that accepts a list of values
)
RETURNS TABLE
AS
RETURN
...code...
GO
不确定如何在TVF中传递几个参数,但这是我如何查看解决方案
SELECT *
FROM dbo.fnExample ('2019-01-01') and ([list of values])
答案 0 :(得分:5)
使用表类型参数,您可以执行以下操作:
CREATE TYPE dbo.SomeArray AS TABLE (SomeInt int); --Create the TYPE
GO
--Now the Function
CREATE FUNCTION dbo.Example (@StartDate date, @Array dbo.SomeArray READONLY)
RETURNS TABLE
AS RETURN
SELECT DATEADD(DAY, SomeInt, @StartDate) AS NewDate
FROM @Array
GO
--Now to test
--Declare the TYPE
DECLARE @Array dbo.SomeArray;
--Insert the data
INSERT INTO @Array (SomeInt)
VALUES(7),(1654),(13);
--Test the function
SELECT *
FROM dbo.Example(GETDATE(), @Array) E;
GO
--Clean up
DROP FUNCTION dbo.Example;
DROP TYPE dbo.SomeArray;
如何JOIN
:
FROM dbo.YourTable YT
JOIN @Array A ON YT.SomeInt = A.SomeInt
如何使用EXISTS
:
WHERE EXISTS (SELECT 1 FROM @Array A WHERE YT.SomeInt = A.SomeInt)
答案 1 :(得分:1)
如果您使用的是SQL Server 2016+,最简单的方法是使用JSON:
CREATE FUNCTION dbo.fnExample
(
@StartDate AS Date -- Parameter 1
@ParameterArray AS NVARCHAR(MAX) -- pass JSON Array like '[1,2,3,4,5]'
)
RETURNS TABLE
AS
RETURN
SELECT TRY_CONVERT(INT,j.value) AS [ID] FROM OPENJSON(@ParameterArray) j;
GO