我将如何结合这两个陈述。基本上这是一个搜索,我希望用户能够搜索姓名,公司或笔记。 Notes在另一个名为act的表中。其中有一个CID的外键。我希望它只返回与已填写的内容相匹配的结果。所以搜索名称:Bob注意:高尔夫不会返回所有在笔记中有高尔夫球的用户,但只会返回名字为bob且在注释字段中有高尔夫球的人。
我遇到的问题是如果Notes确实返回超过1行,那么它会破坏我使用第一行语句的机会。
我正在使用SQL-Server 2005.谢谢
第一声明:
SELECT DISTINCT CID, Name, Comp, Email
From Con
Where (Name IS NULL OR Name LIKE '%' + @name + '%')
AND (Comp IS NULL or Comp LIKE '%' + @comp + '%')
第二声明:
If @notes <> ''
Begin
SET @newid =
(
Select CID
From Act
Where Note LIKE '%' + @notes + '%'
)
Select DISTINCT CID, Name, Comp, Email
From Contacts c
Where (CID= @newid)
End
答案 0 :(得分:0)
SELECT DISTINCT CID, Name, Comp, Email
From Con
Where (Name IS NULL OR Name LIKE '%' + @name + '%')
AND (Comp IS NULL or Comp LIKE '%' + @comp + '%')
AND (
@notes = ''
OR EXISTS (
Select CID
From Act
Where Note LIKE '%' + @notes + '%'
AND @notes <> ''
AND Act.CID = Con.CID
)
)
答案 1 :(得分:0)
SELECT DISTINCT CID, Name, Comp, Email
From Con
Where (Name IS NULL OR Name LIKE '%' + @name + '%')
AND (Comp IS NULL or Comp LIKE '%' + @comp + '%')
UNION ALL
Select DISTINCT CID, Name, Comp, Email
From Contacts c
Where (CID = (Select CID From Act Where @notes <> '' AND Note LIKE '%' + @notes + '%'))