0

在我的数据库中,表的结构类似于:

create table ItemNameSearches
(ItemName varchar(50) not null,timesSearched int not null,
primary key(ItemName))
and

create table ItemList
(ItemName varchar(50),
primary key (ItemName))

我的想法是让人们通过网络表单输入以逗号分隔的值列表,以便他们可以获得有关某些项目的信息。表 ItemList 包含有关他们搜索的项目的信息(尽管在此示例中表结构并未反映这一点)。但是,如果搜索的项目没有出现在 ItemList 表中,我希望将该 ItemName 插入到 ItemNameSearches 中,以便更好地了解人们正在搜索的内容。

场景 1:第一次搜索一个项目,并在 ItemNameSearches 表中插入了一个新行。我很确定这是触发器的区域,但我不熟悉使用它们,所以我编写了以下存储过程:

create proc spSearchItemName
 @itemName1 varchar(50)
,@itemName2 varchar(50) = null
,@itemName3 varchar(50) = null
,@itemName4 varchar(50) = null
as
begin
;with searchList
as
(select x.itemName
 from (values (@itemName1)
,(@itemName2)
,(@itemName3)
,(@itemName4)
 ) as x(itemName)
 where x.itemName is not null
 --these are optional parameters just to give the user more flexibility
 --on if they want to look at multiple items at once or not
)
insert into ItemNameSearches(itemName,timesSearched)
values
(
(select  sl.itemName
from searchList as sl
left outer join ItemList as il
on il.itemName=sl.itemName
where il.itemName is null
--this subquery finds the items searched for that are not present in the
--itemlist table and sets timesSearched =1 for each 
),1
)
end
This is well and good for the items that are searched for that do not appear in the ItemList table, but I would have to do something like the following procedure if they DID search for an item that was in the ItemList table

;with searchList 
as
(select x.itemName
 from (values ('item 1')
,('item 2')
,('item 3')
,('item 5')
 ) as x(itemName)
)

update ins
set  timesSearched = timesSearched +1
from ItemNameSearches as ins
where itemName in
(select itemName from searchList)

因此,如果项目存在于 ItemList 表中,这将使搜索项目的次数增加 1。有人可以提供一种巧妙的方式来解决这两种不同的情况吗?这是一个很好的触发器候选者吗?

4

1 回答 1

0

感谢@Gordon Linoff 提供了使用合并语句的方向,它最终完美地完成了我想做的事情。我最终使用了以下存储过程,它工作正常。

alter proc spSearchDrugName
 @drugName1 varchar(50)
,@drugName2 varchar(50) = null
,@drugName3 varchar(50) = null
,@drugName4 varchar(50) = null
,@drugName5 varchar(50) = null
as
begin
declare @searchList table(drugName varchar(50))
insert into @searchList 
values (@drugName1)
      ,(@drugName2)
      ,(@drugName3)
      ,(@drugName4)
      ,(@drugName5)

    merge DrugListSearches as d
    using(select drugName from @searchList where drugName is not null) as s
    on s.drugName = d.drugName
    when matched then 
        update set d.timesSearched = d.timesSearched + 1
    when not matched then 
    insert (drugname,timesSearched) values (s.drugName,1);



end
于 2013-05-16T19:56:25.100 回答