我覺得這個不能做,如果這是你得到的唯一信息。參數值之間的關係是它們在列表中的位置。在SQL中沒有選擇關聯和/或保留這些位置。
你對創建sql語句有什麼影響?
如果你可以遍歷代碼列表和動態創建的SQL,你能來這樣一個解決方案:
SELECT * FROM Gecoserv
WHERE typeOfEcosystem = 'Freshwater' AND service = 'Habitat'
UNION
SELECT * FROM Gecoserv
WHERE typeOfEcosystem = 'Freshwater' AND service = 'Food'
UNION
...
有關如何參數化這樣的一個例子,看看this answer。
一種替代方案:拆分字符串
你的主要問題是,維護「等級」 /在他們的名單參數的「位置」。這可以通過用字符串替換您的列表並將其分解來完成。
我用這個example of a splitting a string in sql。
(與this 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
做你的表有獨特的鍵(或其他標識列):其它技術(只是普通的老神在讀),可以發現? – wildplasser