please help to fix my sql function!
in my sql function i have one temporary tables
parameter passing to function @searchstring ---- "'%carrots%' AND tmp.ItemDescription like '%baby%'"
Declare @tempvalues table (itemdescription nvarchar(max))
@tempvalues VALUES
-----------------------
CARROTS, BABY, CLASS I, FRESH
CARROTS, BABY, FROZEN
CARROTS, CLASS I, FRESH
------------------
so in function iam passing value for searching data using like query and if matches i need to insert data in another table like
in below temptable if its matching i need to insert 1 as corresponding line
Declare @tempfinal table (itemdescription nvarchar(max),matchcontains int)
**insert into @tempfinal select ItemDescription,'1'as matchcontains from @tempvalues tmp where tmp.ItemDescription like @searchstring**
but nothing is inserting in @tempfinal
i need to search all words match
please help to find a solution
SAMPLE FUNCTION
CREATE FUNCTION dbo.UDF_PredictItems_testfreetextdemo
(
@FTSExpression NVARCHAR(4000)
)
RETURNS @Result TABLE
(
itemdescription NVARCHAR(4000),
matchcontains int
)
AS
BEGIN
Declare @tempvalues table (itemdescription nvarchar(max))
insert into @tempvalues values ('CARROTS, BABY, CLASS I, FRESH') ,
('CARROTS, BABY, FROZEN 2.5 KGS') ,
('CAKE, CARROT, FROZEN 1 KGS') ,
('CARROTS, CLASS I, FRESH')
declare @containExpression nvarchar(max)
set @containExpression =replace(replace(replace(@FTSExpression,' ','<>'),'><',''),'<>',' ')
set @containExpression=(Select replace(@FTSExpression, ' ', '%'))
set @containExpression=(Select replace(@containExpression, ' ', ' AND tmp.ItemDescription like '))
set @containExpression=(select '''%'+@containExpression+'%''')
declare @tempfinal table(ItemDescription nvarchar(max),matchcontains int)
insert into @tempfinal select ItemDescription,CAST('1' AS INT) as matchcontains from @tempvalues tmp where tmp.ItemDescription like @containExpression
insert into @Result ( itemdescription,matchcontains )
select itemdescription,0 from @tempfinal
return;
END
CALLING FUNCTION
SELECT * from UDF_PredictItems_testfreetextdemo('Carrots baby')
I've checked and LIKE
operator as you described that works fine for me.
Declare @tempvalues table (itemdescription nvarchar(max))
INSERT INTO @tempvalues
VALUES ('CARROTS'), ('BABY'), ('CLASS I'), ('FRESH'),('CARROTSI'), ('BABYI'), ('FROZENI'), ('CARROTSI'), ('CLASS I'), ('FRESH')
DECLARE @searchstring NVARCHAR(50) = '%carrots%'
SELECT * FROM @tempvalues WHERE itemdescription LIKE @searchstring
Output:
CARROTS
CARROTSI
CARROTSI
Check my result here
Updated
So the problem not in LIKE
operator, As @Antonios Katopodis's answer, you should insert int
instead of varchar
type
Updated after fixing
Your problem here
set @containExpression=(select '''%'+@containExpression+'%''')
You should fix by this way
set @containExpression=(select '%'+@containExpression+'%')