Preface:You may be surprised: why does the source of inspiration discuss SQL? Perhaps it should be said that it is difficult to engage in a business system and not to relate to SQL.
Scene:In the process of developing a system, I encountered a "related article" function: Any article can define "keywords", each article relies on this "keyword" to determine whether other articles are related to it, if you do not define keywords, you may need to use Full-text search to implement, this is another topic.
thinking:Because the keyword can be defined by a "," delimiter, it makes it more difficult. After thinking, you can save the article by breaking down the key words, creating a key table, all the keywords by the corresponding article ID to save. and decided to adopt a pure SQL stored procedure, because this duplication of operations, rather than using a common function, rather than using precompiled stored procedures faster, so that all processing can be left to SQL Server.
Solution 1:The preferred thing to do is to create a related article table (Relateddetails) based on the original article table (Details), including the Itemid (primary key), Detailid (article ID), and keyword (keyword). The following are the primary stored procedures:
1, updaterelateddetails: Update related article keywords
Copy Code code as follows:
CREATE procedure dbo. Updaterelateddetails
@DetailID INT,
@Keywords 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 the original related article keywords
Copy Code code as follows:
CREATE PROCEDURE dbo. Deleterelateddetails
@DetailID INT
As
DELETE from Detailkeywords WHERE detailid= @DetailID
Go
3, Getrelateddetails: Get related articles, which details is the article table
Copy Code code 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 the Details D right OUTER JOIN detailkeywords k k.detailid=d.itemid WHERE d.itemid <> @DetailID and @Keywords LI KE '% ' +k.keyword+ '% '
End
Go
Current 1/2 page 12 Next read the full text