Sql server 仅当所有动态参数值匹配时才从表中选择
我有以下Sql server 仅当所有动态参数值匹配时才从表中选择,sql-server,tsql,Sql Server,Tsql,我有以下动物表格: id | action ------------------ duck | cuack duck | fly duck | swim pelican | fly pelican | swim 我想创建一个存储过程,并将一组值传递到单个参数中: EXEC GuessAnimalName 'cuack,fly,swim' Result: duck 所以,如果它反刍、飞翔、游泳,那它就是一只鸭子。而且: EXEC GuessAnimalNa
动物表格:
id | action
------------------
duck | cuack
duck | fly
duck | swim
pelican | fly
pelican | swim
我想创建一个存储过程,并将一组值传递到单个参数中:
EXEC GuessAnimalName 'cuack,fly,swim'
Result:
duck
所以,如果它反刍、飞翔、游泳,那它就是一只鸭子。而且:
EXEC GuessAnimalName 'fly,swim'
Result:
pelican
---
EXEC GuessAnimalName 'fly'
Result:
No results
参数的编号是动态的
为了猜测动物的名字,提供的所有动作必须匹配或在动物表中找到。
这就是我到目前为止所做的:
DECLARE @animal AS TABLE
(
[id] nvarchar(8),
[action] nvarchar(16)
)
INSERT INTO @animal VALUES('duck','cuack')
INSERT INTO @animal VALUES('duck','fly')
INSERT INTO @animal VALUES('duck','swim')
INSERT INTO @animal VALUES('pelican','fly')
INSERT INTO @animal VALUES('pelican','swim')
-- Parameter simulation
DECLARE @params AS TABLE
(
[action] nvarchar(16)
)
INSERT INTO @params VALUES('cuack')
INSERT INTO @params VALUES('fly')
INSERT INTO @params VALUES('swim')
SELECT
a.[id]
FROM
@animal a
INNER JOIN
@params p
ON
a.[action] = p.[action]
GROUP BY
a.[id]
HAVING COUNT(a.[action]) IN (SELECT COUNT([action]) FROM @animal GROUP BY [id])
结果如下:
Result:
--------
duck
--------
pelican
它应该只返回duck
使用RANK
declare @lookfor varchar(100) = 'swim,fly'
select id from
(select
id, rank() over (order by cnt desc) rank_ -- get rank based on the number of match where should be the same number of rows
from
(
SELECT
a.id, count(1) cnt -- identify how many matches
FROM
@animal a
INNER JOIN
@params p
ON
a.[action] = p.[action]
where charindex(p.action,@lookfor) > 0
group by a.id
having count(1) = (select count(1) from @animal x where a.id = x.id)) -- only get the animal with the same number of matches and rows
y)
z where rank_ = 1 -- display only with the most matches which should be the same number of rows matched
这里不需要@params
select id from
(select
id, rank() over (order by cnt desc) rank_
from
(
SELECT
a.id, count(1) cnt
FROM
@animal a
where charindex(a.action,@lookfor) > 0
group by a.id
having count(1) = (select count(1) from @animal x where a.id = x.id))
y)
z where rank_ = 1
如果我通过飞行,游泳,它会返回鸭子。所有参数必须匹配,因此它应该返回鹈鹕
。编辑后,如果我通过飞,游
,它将返回鸭
和鹈鹕
。是的。。应该同时返回。。。如果有一个cuack,那么应该只有duckduck
应该被丢弃,因为没有提供cuack
参数,这是要求。hmmm。。我可能误解了你的要求。让我再查一下