简体   繁体   English

SQL Server(2005)查询帮助

[英]SQL Server (2005) Query Help

My query is based on the following example 我的查询基于以下示例

I have table say 'Table1'. 我的桌子说“ Table1”。 Table1 has one row and one column. 表1具有一行和一列。 The name of the column is 'Column1'. 列的名称为“ Column1”。 'Column1' is a text column (NVARCHAR). “ Column1”是文本列(NVARCHAR)。 I have a comma separated keywords like 'key1,key2..keyn'. 我有一个逗号分隔的关键字,例如“ key1,key2..keyn”。 I want to search these keywords individually in the column1. 我想在column1中分别搜索这些关键字。

So in the where clause the query should be something like 因此,在where子句中,查询应类似于

SELECT ... FROM Table1
WHERE Column1 LIKE '%key1%'
AND Column1 LIKE '%key2%'
AND Column1 LIKE '%keyn%'

I just want to know how to write a query in a simplified manner. 我只想知道如何以简化的方式编写查询。 Table is quite small and performance is not a main concern. 表很小,性能不是主要问题。

Just declare the keywords in a variable for the test case 只需在测试用例的变量中声明关键字

DECLARE @Keywords NVARCHAR(MAX)
SET @Keywords = 'Key1,Key2,Key3'

A simple example will be helpful to me. 一个简单的例子对我会有所帮助。

This will be easier if you get these into table format. 如果将它们转换成表格格式,这将更加容易。 ( Split Table Valued functions exist to do this to your delimited string - eg http://www.eggheadcafe.com/community/aspnet/13/10021854/fnsplit.aspx ) (存在Split表值函数来对分隔的字符串执行此操作-例如http://www.eggheadcafe.com/community/aspnet/13/10021854/fnsplit.aspx

DECLARE @Keywords TABLE
(
COL NVARCHAR(100)
)

INSERT INTO @Keywords SELECT 'Key1' UNION ALL SELECT 'Key2' UNION ALL SELECT 'Key3'

SELECT ... 
FROM Table1  c 
JOIN @Keywords k ON c.Column1  LIKE '%' + k.COL + '%'
GROUP BY  ...
HAVING COUNT(*) = (select COUNT(*) FROM @Keywords)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM