在我的数据库中,表的结构类似于:
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。有人可以提供一种巧妙的方式来解决这两种不同的情况吗?这是一个很好的触发器候选者吗?