Preface: Everyone may be surprised: Why is the source of inspiration discussing SQL? Perhaps we should say this: it seems difficult to establish a business system that does not relate to SQL.
Scenario:In the process of developing a system, I encountered the need to implement "relatedArticle"Function: any article can define a" keyword ". Each article depends on this" keyword "to determine whether other articles are related to it. If no keyword is defined, you may need to use full-text search. This is another topic.
Thoughts:Because multiple keywords can be defined using the "," separator number, the difficulty is increased. After thinking, you can break down the keywords when saving the article, create a keyword table, and save all the keywords one by one based on the corresponding article Id. And decided to adopt the pure SQL stored procedure method, because this repeated operation, with the use of common functions, is better than the use of pre-compiled stored procedures to accelerate, so that all the processing can be left to the SQL server.
Solution 1:The first choice is to create a relateddetails table based on the original article table (details). The fields include Itemid (Primary Key), detailid (Article ID), and keyword (keyword ). The following are the main stored procedures:
1. updaterelateddetails: updates related keywordCopyCodeThe Code is as follows: Create procedure DBO. updaterelateddetails
@ Detailid int,
@ Key words nvarchar (500)
As
Exec deleterelateddetails @ detailid
Declare @ I int
Declare @ keyword nvarchar (50)
Set @ KEYWORDS = Replace (@ keywords ,',',',')
Set @ KEYWORDS = Replace (@ keywords ,';',',')
Set @ KEYWORDS = rtrim (ltrim (@ keywords ))
Set @ I = charindex (',', @ keywords)
While @ I> = 1
Begin
Set @ keyword = left (@ keywords, @ I-1)
Insert into detailkeywords (detailid, keyword) values (@ detailid, @ keyword)
Set @ KEYWORDS = substring (@ keywords, @ I + 1, Len (@ keywords)-@ I)
Set @ I = charindex (',', @ keywords)
End
If @ keywords <>''
Insert into detailkeywords (detailid, keyword) values (@ detailid, @ keywords)
Go
2. deleterelateddetails: delete original related article keywordsCopy codeThe Code is as follows: Create procedure DBO. deleterelateddetails
@ Detailid int
As
Delete from detailkeywords where detailid = @ detailid
Go
3. getrelateddetails: Get related articles. The details is the article table.Copy codeThe Code is as follows: Create procedure DBO. getrelateddetails
@ Detailid int
As
Declare @ keywords nvarchar (500)
Select @ KEYWORDS = keywords from details where Itemid = @ detailid
If @ keywords <>''
Begin
Select distinct D. Itemid, D. Subject, D. itemfile
From details D right Outer Join detailkeywords K on K. detailid = D. Itemid where D. Itemid <> @ detailid and @ keywords like '%' + K. Keyword + '%'
End
Go