SQL Server:在表的所有列中查找特定单词

时间:2015-07-01 14:05:42

标签: sql-server

我想在特定表的所有列中找到特定单词。 我试过这个sql select * from TestData where 'bisu' in (Name1,Name2,Name3) 当列仅包含单词bisu但列包含类似文本时,它可以工作 Welcome bisu然后我的上面的sql失败了。

我遵循以下方法,但有点大。所以任何人都告诉我,如何通过普通的SQL而不是调用存储过程来完全满足我的要求。

CREATE PROCEDURE sp_FindStringInTable @stringToFind VARCHAR(100), @schema sysname, @table sysname
AS

DECLARE @sqlCommand VARCHAR(8000)
DECLARE @where VARCHAR(8000)
DECLARE @columnName sysname
DECLARE @cursor VARCHAR(8000)

BEGIN TRY
   SET @sqlCommand = 'SELECT * FROM [' + @schema + '].[' + @table + '] WHERE'
   SET @where = ''

   SET @cursor = 'DECLARE col_cursor CURSOR FOR SELECT COLUMN_NAME
   FROM ' + DB_NAME() + '.INFORMATION_SCHEMA.COLUMNS
   WHERE TABLE_SCHEMA = ''' + @schema + '''
   AND TABLE_NAME = ''' + @table + '''
   AND DATA_TYPE IN (''char'',''nchar'',''ntext'',''nvarchar'',''text'',''varchar'')'

   EXEC (@cursor)

   OPEN col_cursor   
   FETCH NEXT FROM col_cursor INTO @columnName   

   WHILE @@FETCH_STATUS = 0   
   BEGIN   
       IF @where <> ''
           SET @where = @where + ' OR'

       SET @where = @where + ' [' + @columnName + '] LIKE ''' + @stringToFind + ''''
       FETCH NEXT FROM col_cursor INTO @columnName   
   END   

   CLOSE col_cursor   
   DEALLOCATE col_cursor 

   SET @sqlCommand = @sqlCommand + @where
   --PRINT @sqlCommand
   EXEC (@sqlCommand) 
END TRY
BEGIN CATCH
   PRINT 'There was an error. Check to make sure object exists.'
   IF CURSOR_STATUS('variable', 'col_cursor') <> -3
   BEGIN
       CLOSE col_cursor   
       DEALLOCATE col_cursor 
   END
END CATCH 

EXEC sp_FindStringInTable 'Irv%', 'Person', 'Address'

感谢

2 个答案:

答案 0 :(得分:0)

你应该尝试以下,

Select 
 *
From TestData
Where 
1 = case when name1 like '%bisu%' then 1 else 0 end 
And 1 = case when name2 like '%bisu%' then 1 else 0 end 
And 1 = case when name3 like '%bisu%' then 1 else 0 end 

答案 1 :(得分:0)

只是从谷歌搜索各种答案,发现一个很好的答案,它的确有效。

select * from TestData
WHERE  Name1 + Name2 + Name3 like '%bisu%'