Hỏi đáp
Chia sẻ kiến thức, cùng nhau phát triển
Code SQL tìm kiếm theo nhiều trường
21:56 12-07-2017
913 lượt xem
0 bình luận
10:52 13-07-2017
Các bạn xem code này để tham khảo cho case của mình nhé. Tìm kiếm theo nhiều trường kết hợp. Bao nhiêu cũng quẩy được.
CREATE PROC Proc_Search_Document
@keyword NVARCHAR(500),
@branchID INT,
@levelID INT,
@listTagID NVARCHAR(500),
@pageNum INT,
@pageSize INT
AS
BEGIN
--SELECT * FROM dbo.Tag WHERE Name = 'c#'
DECLARE @SQL NVARCHAR(max)
--SELECT DISTINCT d.Title, d.ShortDescription, D.TimeActive, U.RealName, U.Avatar, U.ReputationPoint, D.LastActiveType, D.TagName, L.Name, D.TotalVote, D.TotalView, D.TotalDiscussion FROM dbo.Doc_Document AS D JOIN dbo.Level AS L ON D.LevelId=L.Id JOIN dbo.InformationUser AS U ON D.UserIdLastActive = U.Id
--ORDER BY D.TimeActive DESC OFFSET (@pageNum - 1) * @pageSize ROWS FETCH NEXT @pageSize ROWS only
-- JOIN dbo.Doc_TagInDocument AS T ON D.Id = t.DocumentId WHERE t.TagId IN (@listTagID)
--SELECT D.Published, D.Deleted, D.ImproveId, D.UserId,D.Draft, D.UserIdLastActive, D.Id FROM dbo.Doc_Document AS D, dbo.InformationUser AS U
SET @SQL = 'SELECT DISTINCT
d.Title,
d.ShortDescription,
d.Image,
D.TimeActive,
U.RealName,
U.Avatar,
U.ReputationPoint,
D.LastActiveType,
D.TagName,
L.Name as LevelName,
D.TotalVote,
D.TotalView,
D.TotalDiscussion,
D.Published,
D.Deleted,
D.ImproveId,
D.UserId,
D.Draft,
D.UserIdLastActive,
D.Id
FROM dbo.Doc_Document AS D
JOIN dbo.Level AS L ON D.LevelId=L.Id
JOIN dbo.InformationUser AS U ON D.UserIdLastActive = U.Id '
DECLARE @IsHavaParam BIT = 0
IF (@listTagID IS not NULL AND @listTagID <> '')
BEGIN
SET @IsHavaParam = 1
SET @SQL = @SQL + ' JOIN dbo.Doc_TagInDocument AS T ON D.Id = t.DocumentId WHERE t.tagID IN (' + @listTagID + ') '
END
IF (@keyword IS NOT NULL and @keyword <>'')
BEGIN
IF (@IsHavaParam = 0)
BEGIN
SET @SQL = @SQL + ' where '
SET @IsHavaParam = 1
END
ELSE
BEGIN
SET @SQL = @SQL + ' and '
END
SET @SQL = @SQL + ' Title LIKE N''%' + @keyword + '%'''
END
IF (@branchID IS not NULL AND @branchID <> -1)
BEGIN
IF (@IsHavaParam = 0)
BEGIN
SET @SQL = @SQL + ' where '
SET @IsHavaParam = 1
END
ELSE
BEGIN
SET @SQL = @SQL + ' and '
END
SET @SQL = @SQL + ' BranchId = ' + CAST(@branchID AS NVARCHAR(10))
END
IF (@levelID IS NOT NULL AND @levelID <> -1)
BEGIN
IF (@IsHavaParam = 0)
BEGIN
SET @SQL = @SQL + ' where '
SET @IsHavaParam = 1
END
ELSE
BEGIN
SET @SQL = @SQL + ' and '
END
SET @SQL = @SQL + 'LevelId = ' + CAST(@levelID AS NVARCHAR(10))
END
SET @SQL = @SQL + ' ORDER BY D.TimeActive DESC OFFSET ' + cast((@pageNum - 1) * @pageSize AS nvarchar(10)) + ' ROWS FETCH NEXT '+ CAST(@pageSize AS NVARCHAR(10)) +' ROWS ONLY '
PRINT @SQL
EXEC sp_executesql @SQL
END
GO