将创建的列添加到搜索条件?

时间:2013-07-11 13:09:08

标签: sql

下面是我搜索所有列的搜索表格。我已经添加了CleanName列,并且需要在其他查询中搜索,原因是如果我当前搜索“bob smith”即时获得0匹配但是bob返回匹配因为名字,所以在这个示例中,cleanname是actaully full名称

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 

2 个答案:

答案 0 :(得分:0)

不,您只能在WHERE子句中使用来自源(或包含这些列的表达式)的列

通常你会以这种方式将它添加到WHERE子句中:

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

但是用你选择的方法做到这一点可能是不可能的。

答案 1 :(得分:0)

添加此行

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

在set语句修复了我的问题

之后