我正在创建一个函数,作为参数,我需要一个动态的数字列表。我的理解是,我不能将此作为参数,所以我试图在CTE中定义列表。以下是我的代码的开头:
CREATE FUNCTION dbo.fnRCPolicyDetailByForm (@formcategory INT)
RETURNS TABLE
RETURN
WITH FormBase_CTE AS (
SELECT
CASE
WHEN @formcategory = 1 THEN (SELECT 1,2,3)
WHEN @formcategory = 2 THEN (SELECT 4,5)
ELSE NULL
END AS Forms
)
我收到此错误:
当选择列表中只能指定一个表达式时 子查询不是用EXISTS引入的。
我试图实现的目标还有其他解决办法吗?
答案 0 :(得分:0)
解决方法:
SELECT 1 WHERE @formcategory = 1
UNION ALL
SELECT 2 WHERE @formcategory = 1
UNION ALL
SELECT 3 WHERE @formcategory = 1
UNION ALL
SELECT 4 WHERE @formcategory = 2
或者您可以使用STRING_SPLIT - https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql
DECLARE @FILTERS NVARCHAR(MAX) = CASE WHEN @fromcategory = 1 THEN '1,2,3' ELSE '4' END
SELECT VALUE FROM STRING_SPLIT(@FILTERS, ',')
编辑:将XML用于旧服务器版本
DECLARE @formcategory int = 1
DECLARE @filter xml = CASE WHEN @formcategory = 1 THEN '<v>1</v><v>2</v><v>3</v>'
ELSE '<v>4</v><v>5</v>'
END
SELECT T.c.value('.', 'int') AS Value FROM @filter.nodes('/v') AS T(C)