如果我有一个等于“Hello Connor Mcgregor”的搜索词,那么我该如何使用这个搜索词,以便搜索词循环列表中的每个搜索词,例如:
searchTerm[0] = "Hello";
searchTerm[1] = "Conner"
searchTerm[2] = "Mcgregor"
并在表中搜索用一个字段或两个字段分隔的每个值并返回该行。
在过去的几年里,我一直在使用 EntityFramework,但我一直在 LINQ 中尝试它,发现最好使用 ADO.NET 并使用存储过程。
已经尝试过:
DECLARE @pos INT
DECLARE @len INT
DECLARE @value nvarchar(80)
DECLARE @sql nvarchar(max)
set @pos = 0
set @len = 0
WHILE CHARINDEX(' ', @searchTerm, @pos+1) > 0
BEGIN
set @len = CHARINDEX(',', @searchTerm, @pos+1) - @pos
set @value = SUBSTRING(@searchTerm, @pos, @len)
if exists (select title, questionText from tblThread where title like @value + '%')
BEGIN
set @sql = (select title, questionText from tblThread where title like @value + '%')
Print @sql
--DO YOUR MAGIC HERE
END
set @pos = CHARINDEX(',', @searchTerm, @pos+@len) +1
END
我尝试过这个,但似乎无法在临时表中添加值
ALTER PROCEDURE [dbo].[getThreadsBySearchTerm]
@searchTerm nvarchar(80)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @searchTermTbl TABLE (searchTerm nvarchar(max))
DECLARE @value nvarchar(max)
DECLARE @pos INT
DECLARE @len INT
DECLARE @sql nvarchar(max)
DECLARE @sqlWithSpace Int
set @pos = 0
set @len = 0
while CHARINDEX(' ', @searchTerm, @pos+1) > 0
Begin
set @len = CHARINDEX(' ', @searchTerm, @pos+1) - @pos
set @value = SUBSTRING(@searchTerm, @pos, @len)
insert into @searchTermTbl values(@value)
set @pos = CHARINDEX(' ', @searchTerm, @pos+@len) +1
End
if exists(select * from @searchTermTbl)
begin
select title, questionText from tblThread
inner join @searchTermTbl stt on tblThread.title Like '%' + stt.searchTerm + '%'
inner join @searchTermTbl sttt on tblThread.questionText Like '%' + sttt.searchTerm + '%'
end
else
begin
select title, questionText from tblThread
where title like '%' + @searchTerm + '%'
or questionText like '%' + @searchTerm + '%'
end
select * from @searchTermTbl
END
GO
exec getThreadsBySearchTerm 'Question is'
它添加了“问题”,但没有添加“是”