SQL通配符而不是SELECT语句中的键

时间:2012-03-30 13:22:06

标签: sql sql-server-2008 wildcard

我能以一种干净的方式做到:

SELECT * 
FROM tablename 
WHERE * LIKE '%something%';

无需做:

SELECT * 
FROM tablename 
WHERE ColA LIKE '%something%' 
   OR ColB LIKE '%something%' ...;

运行SQL Server 2008,我收到错误:

  

“无法在表或索引视图上使用CONTAINS或FREETEXT谓词   'tablename'因为它没有全文索引。

我没有全文索引:)

6 个答案:

答案 0 :(得分:3)

要建立@Bob Probst的想法,你可以尝试这样dynamic SQL

-- Set these!
declare @tableName nvarchar(128)= 'MyTableName'
declare @searchString nvarchar(max)= '%something%'

-- Build SQL query
declare @sql nvarchar(max)
select @sql = isnull(@sql + 'or ', 'select * from ' + @tableName + ' where ' )
    + '[' + column_name + '] like ''' + replace(@searchString, '''', '''''') + ''' '
from information_schema.columns
where table_name = @tableName
    -- Could use this where clause for only comparing string fields (or eliminating image and such)
    --and data_type in ('varchar', 'char','nvarchar', 'nchar')

-- Run SQL query
print (@sql) -- For debug
exec (@sql)

答案 1 :(得分:2)

您可以像这样编写脚本:

select 'select * from dbo.ACCOUNT_DIMENSION where '
union all
select c.name+' like ''%something%'' or '
from sys.tables t
inner join sys.columns c on (t.object_id=c.object_id)
where t.name = 'ACCOUNT_DIMENSION'
union all
select '1=1'

答案 2 :(得分:1)

没有。这是不可能的。你必须写字段名。

答案 3 :(得分:0)

CONTAINS *声音怎么样?

Use AdventureWorks2008R2;
GO
SELECT Name, Color FROM Production.Product
WHERE CONTAINS((Name, Color), 'Red');

*这需要全文索引

答案 4 :(得分:0)

您应该能够使用+号将ColA和ColB绑定在一起:

SELECT 
   * 
FROM 
   tablename 
WHERE 
   ColA+ColB Like '%something%'

答案 5 :(得分:0)

没有全文索引,动态执行此操作的唯一方法是使用动态构建的语句;

declare @sql varchar(max) = 'select * from tablename where 1=0'

select @sql += ' or ' + quotename(column_name) + ' like ''%something%'''
from information_schema.columns
where TABLE_NAME = 'tablename'
and data_type in ('char', 'varchar', 'nchar', 'nvarchar')

exec(@sql)