我认为这是无法做到的,因为这是您获得的唯一信息。参数值之间的关系是它们在列表中的位置。没有选项可以在 SQL 中关联和/或保留这些位置。
您对创建 sql 语句有什么影响?
如果您可以遍历代码中的列表并动态创建 sql,您可以找到如下解决方案:
SELECT * FROM Gecoserv
WHERE typeOfEcosystem = 'Freshwater' AND service = 'Habitat'
UNION
SELECT * FROM Gecoserv
WHERE typeOfEcosystem = 'Freshwater' AND service = 'Food'
UNION
...
有关如何参数化的示例,请查看此答案。
另一种选择:拆分字符串
您的主要问题是在其列表中保留参数的“等级”/“位置”。这可以通过用字符串替换列表并将它们分解来完成。
我使用了这个在 sql 中拆分字符串的示例。
生成的查询(使用此 Fiddle进行)如下所示:
DECLARE
@ecoSystems varchar(100) = 'Freshwater,Saltwater,Dunes',
@services varchar(100) = 'Habitat,Food,Recreation',
@separator char(1) = ','
SELECT
[g].[id],
[g].[typeOfEcoSystem],
[g].[service]
FROM [dbo].[Split](@separator, @ecoSystems) [e]
INNER JOIN [dbo].[Split](@separator, @services) [s]
ON [e].[position] = [s].[position]
INNER JOIN [Gecoserv] [g]
ON [e].[part] = [g].[typeOfEcoSystem]
AND [s].[part] = [g].[service]
ORDER BY [id] ASC
这适用于您的场景吗?(答案:是的,几乎……)
最后没有功能
DECLARE
@ecoSystems varchar(100) = 'Freshwater,Saltwater,Dunes',
@services varchar(100) = 'Habitat,Food,Recreation',
@separator char(1) = ',';
WITH [EcoSystemsAndServices]([posE], [startE], [endE], [posS], [startS], [endS])
AS
(
SELECT
1,
1,
CHARINDEX(@separator, @ecoSystems),
1,
1,
CHARINDEX(@separator, @services)
UNION ALL
SELECT
[posE] + 1,
[endE] + 1,
CHARINDEX(@separator, @ecoSystems, [endE] + 1),
[posS] + 1,
[endS] + 1,
CHARINDEX(@separator, @services, [endS] + 1)
FROM [EcoSystemsAndServices]
WHERE [endE] > 0
)
SELECT
[g].[id],
[g].[typeOfEcoSystem],
[g].[service]
FROM [Gecoserv] [g]
INNER JOIN [EcoSystemsAndServices] [ess]
ON [g].[typeOfEcoSystem] = SUBSTRING(@ecoSystems,
[startE],
CASE WHEN [endE] > 0 THEN [endE] - [startE] ELSE 100 END)
AND [g].[service] = SUBSTRING(@services,
[startS],
CASE WHEN [endS] > 0 THEN [endS] - [startS] ELSE 100 END)
ORDER BY [id] ASC