Select上的独特联盟.ntext数据类型的错误

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但在某些情况下返回重复的行(取决于关键字/短语).

我也尝试使用临时表并选择不同的,但这就是我真的很困惑的地方.

规则:

  • 我无法更改数据类型
  • 我需要'Name'上的select行位于'Description'上select的行上方
  • 我只能使用1个存储过程,并且无法更改数据适配器,因为我将其插入到我无法控制的系统中.

更多信息:

表列(我正在使用的重要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会很棒.:)

Arv*_*rvo 7

使用类似'cast(描述为nvarchar(2000))作为描述'而不是ntext字段名称.


dav*_*all 5

这个答案适用于像我这样的人,不会出现重复行的问题.

UNION ALL 可能就是你想要的.

请参阅UNION运算符文档.


Mar*_*ith 4

从评论来看。看来这就是你所需要的。

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)

您可能需要考虑为此使用全文搜索,因为带有前导通配符的搜索无法使用索引,并且始终需要扫描所有行。