I am trying to get some data using parameters on my query, but the problem is that these parameters are just a part of the content.
my table would be something like the following:
|columnName
1 | AAA-XX
2 | AAA-YY
3 | AAA-ZZ
4 | BBB-BB
5 | BBB-CC
6 | BBB-11
5 | CCC-AA
6 | DDD-FF
the problem is that my application only knows the part before the "-", so I have a list like ["AAA", "DDD"]. I am able to use "like" to get one parameter, but I need to use a list of them dynamically.
Is there a way to do something like this:
SELECT *
FROM myTable
WHERE columnName like '@[names]%'
where names = ["AAA", "DDD"] and get the result like this:
|columnName
1 | AAA-XX
2 | AAA-YY
3 | AAA-ZZ
4 | DDD-FF
Just to clarify, the list names changes all the time (it might be ["BBB", "CCC", "DDD"] or even ["CCC"]) depending on my application needs so a hardcoded solution won't work for me.
My application is built on C# and the request is bult using DynamicParameters.Add("@[names]", names, DbType.string), this way the only thing I know of is the query string, I cannot pass any hardcoded parameters to it.
You can simply use OR
.
SELECT columnname
FROM elbat
WHERE columnname LIKE '<value_1>%'
...
OR columnname LIKE '<value_n>%';
For 'AAA'
and 'DDD'
that would look like:
SELECT columnname
FROM elbat
WHERE columnname LIKE 'AAA%'
OR columnname LIKE 'DDD%';
Or join a VALUES
clause with the names.
SELECT elbat.columnname
FROM elbat
INNER JOIN (VALUES ('<value_1>'),
...
('<value_n>')) names (name)
ON elbat.columnname LIKE concat(names.name, '%');
Again for 'AAA'
and 'DDD'
that would look like:
SELECT elbat.columnname
FROM elbat
INNER JOIN (VALUES ('AAA'),
('DDD')) names (name)
ON elbat.columnname LIKE concat(names.name, '%');
create table #temp
( columnname varchar(50)
)
insert into #temp values ('AAA-XX'), ('AAA-YY'), ('AAA-ZZ'), ('BBB-BB'), ('BBB-CC'), ('BBB-11'), ('CCC-AA'), ('DDD-FF')
declare @string varchar(50) = 'AAA,BBB,CCC';
SELECT *
FROM #temp t
JOIN string_split (@string, ',') s
on columnname like s.value + '%'
You may also use Substring if you want.
SELECT *
FROM #temp t
JOIN string_split (@string, ',') s
on s.value = SUBSTRING (columnname, 1, CHARINDEX('-', columnname) - 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.