我在SQL Server中创建存储过程如下:
CREATE PROCEDURE [dbo].[SearchData]
@searchText varchar(500)
AS
BEGIN
SET NOCOUNT ON
SELECT TOP 50
s.[MaxRank] AS [Rank],
sc.TaskSourceId,
c.IndividualName,
c.EntityName,
c.Text
FROM
(SELECT
MAX(s.Rank) AS MaxRank,
MAX(c.CaptureId) AS MaxCaptureId,
c.TaskSourceId
FROM
FreeTextTable(Data.SearchData,
(Identifier, IndividualName, EntityName, [Text]), @searchText) s
JOIN
Data.Capture c ON s.[Key] = c.CaptureId
GROUP BY
c.TaskSourceId) s
JOIN
Data.Capture c ON c.CaptureId = s.MaxCaptureId
JOIN
Data.Source sc ON c.TaskSourceId = sc.TaskSourceId
ORDER BY
s.MaxRank DESC
END
以上执行成功,但包含一些结果,其中Text字段是唯一包含数据的字段,其他字段为NULL。我想添加一个条件,在返回的结果中,IndividualName不能为null或EntityName不能为null。
我无法确定将其放在何处以及确切的语法。
答案 0 :(得分:2)
我认为你的意思是其中一个字段可以为空。如果是这样的话:
CREATE PROCEDURE [dbo].[SearchData]
@searchText varchar(500)
AS BEGIN SET NOCOUNT ON
select top 50 s.[MaxRank] as [Rank],
sc.TaskSourceId,
c.IndividualName,
c.EntityName,
c.Text
from (
select max(s.Rank) as MaxRank,
max(c.CaptureId) as MaxCaptureId,
c.TaskSourceId
from FreeTextTable(Data.SearchData,
(Identifier, IndividualName, EntityName, [Text]),
@searchText) s
join Data.Capture c
on s.[Key] = c.CaptureId
group by c.TaskSourceId
) s
join Data.Capture c
on c.CaptureId = s.MaxCaptureId
join Data.Source sc
on c.TaskSourceId = sc.TaskSourceId
where not (c.IndividualName is null and c.EntityName is null) -- excludes results where both are null
order by s.MaxRank desc
END
答案 1 :(得分:2)
您可以在两列上执行isnull并检查以确保该值不为null,如下所示:
CREATE PROCEDURE [dbo].[SearchData]
@searchText varchar(500)
AS BEGIN SET NOCOUNT ON
select top 50 s.[MaxRank] as [Rank],
sc.TaskSourceId,
c.IndividualName,
c.EntityName,
c.Text
from (
select max(s.Rank) as MaxRank,
max(c.CaptureId) as MaxCaptureId,
c.TaskSourceId
from FreeTextTable(Data.SearchData,
(Identifier, IndividualName, EntityName, [Text]),
@searchText) s
join Data.Capture c
on s.[Key] = c.CaptureId
group by c.TaskSourceId
) s
join Data.Capture c
on c.CaptureId = s.MaxCaptureId
join Data.Source sc
on c.TaskSourceId = sc.TaskSourceId
where not isnull(c.IndividualName, c.EntityName) is null
order by s.MaxRank desc
END
答案 2 :(得分:0)
您也可以在连接条件中使用这些条件。
CREATE PROCEDURE [dbo].[SearchData]
@searchText varchar(500)
AS BEGIN SET NOCOUNT ON
select top 50 s.[MaxRank] as [Rank],
sc.TaskSourceId,
c.IndividualName,
c.EntityName,
c.Text
from (
select max(s.Rank) as MaxRank,
max(c.CaptureId) as MaxCaptureId,
c.TaskSourceId
from FreeTextTable(Data.SearchData,
(Identifier, IndividualName, EntityName, [Text]),
@searchText) s
join Data.Capture c
on s.[Key] = c.CaptureId
group by c.TaskSourceId
) s
join Data.Capture c
on c.CaptureId = s.MaxCaptureId AND (c.IndividualName IS NOT NULL OR c.EntityName IS NOT NULL)
join Data.Source sc
on c.TaskSourceId = sc.TaskSourceId
order by s.MaxRank desc
END