2013-07-11 38 views
1

下面是我的搜索表程序,它搜索所有列。我添加了CleanName列,並且需要在其他查詢中搜索,原因是如果我當前搜索「bob smith」即時消息獲得0個匹配,但bob返回匹配包含名字,因此在此示例中,cleanname實際上已滿命名添加創建列來搜索critera?

USE [ITAPP] 
GO 
/****** Object: StoredProcedure [dbo].[sp_SearchAllTables] Script Date: 07/11/2013 10:57:43 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER PROC [dbo].[sp_SearchAllTables] 
(
    @SearchStr nvarchar(255) 
) 
AS 
BEGIN 

declare @where varchar(8000) 
declare @sql varchar(8000) 
set @sql = 'select u.*,e.*, (u.Forename + '' '' + u.Surname) AS CleanName from tblUsers u join tblEquipment e on e.userid = u.id WHERE 1 = 1 AND (1= 0 ' 

select @where = coalesce(@where ,'') + ' OR ' + case when object_name(object_id) = 'tblUsers' then 'u' else 'e' end + '.[' + name + '] LIKE ''%' + replace(@SearchStr, '''', '''''') + '%'' ' 
from sys.columns where object_id in (select object_id from sys.objects where name in ('tblUsers','tblEquipment')) 
and collation_name is not null 
set @where = coalesce(@where, '') + ')' 

print @sql 
print @where 

exec(@sql + @where) 

END 

回答

0

加入這一行

select @where = ' OR u.[Forename] + '' '' + u.[Surname] LIKE ''%' + replace(@SearchStr, '''', '''''') + '%''' 

SET語句後固定我的問題

0

不行,你只能使用從源(或包含這些列的表達式)列WHERE子句中

通常你把它添加到WHERE條款是這樣的:

WHERE (u.Forename + '' '' + u.Surname) LIKE '%' + @SearchStr + '%' 

但是用你選擇的方法做到這一點可能是不可能的。