Dea*_*per 8 sql sql-server sql-server-2008-r2
我在SQL上没用,但我发现自己必须编写一个存储过程来进行非常简单的关键短语搜索.
我试图在名称上做一个简单的选择 - 像%keyword% - 然后在Description -same关键字上另一个选择 - 并加入(联合)2个选择.
但是,我收到错误:
The ntext data type cannot be selected as DISTINCT because it is not comparable.
Run Code Online (Sandbox Code Playgroud)
我尝试使用UNION ALL
但在某些情况下返回重复的行(取决于关键字/短语).
我也尝试使用临时表并选择不同的,但这就是我真的很困惑的地方.
规则:
更多信息:
表列(我正在使用的重要2是名称和描述):
ProductId int
Name varchar(255)
Introduction varchar(255)
Description ntext
Material ntext
Colour varchar(255)
Active bit
Dimensions varchar(255)
Photo varchar(255)
Price decimal(10, 2)
DisplayOrder int
ProductReference varchar(255)
CategoryId int
FriendlyURL varchar(1000)
Run Code Online (Sandbox Code Playgroud)
SQL:
(SELECT Products.ProductId, Name, Introduction, Description, Active,
Material, Colour, Dimensions, Photo, Price, DisplayOrder, FriendlyURL,
ProductReference, Categories_Products_Lookup.CategoryId
FROM Products INNER JOIN
Categories_Products_Lookup ON
Products.ProductId = Categories_Products_Lookup.ProductId
WHERE Active = 1 AND tProduct.Name like '%'+@Keyword+'%')
UNION
(SELECT Products.ProductId, Name, Introduction, Description, Active,
Material, Colour, Dimensions, Photo, Price, DisplayOrder, FriendlyURL,
ProductReference, Categories_Products_Lookup.CategoryId
FROM ProductsINNER JOIN
Categories_Products_Lookup ON
Products.ProductId = Categories_Products_Lookup.ProductId
WHERE Active = 1 AND Products.Description like '%'+@Keyword+'%')
Run Code Online (Sandbox Code Playgroud)
任何帮助摆脱不同行的表将非常感激.另外,向我解释一下Layman会很棒.:)
从评论来看。看来这就是你所需要的。
SELECT Products.ProductId,
Name,
Introduction,
Description,
Active,
Material,
Colour,
Dimensions,
Photo,
Price,
DisplayOrder,
FriendlyURL,
ProductReference,
Categories_Products_Lookup.CategoryId
FROM Products
INNER JOIN Categories_Products_Lookup
ON Products.ProductId = Categories_Products_Lookup.ProductId
WHERE Active = 1
AND ( Products.Description like '%' + @Keyword + '%'
or Products.Name like '%' + @Keyword + '%' )
ORDER BY CASE
WHEN Products.Name like '%' + @Keyword + '%' THEN 0
ELSE 1
END
Run Code Online (Sandbox Code Playgroud)
您可能需要考虑为此使用全文搜索,因为带有前导通配符的搜索无法使用索引,并且始终需要扫描所有行。
归档时间: |
|
查看次数: |
18822 次 |
最近记录: |