下面是我搜索所有列的搜索表过程。我已经动态添加了 CleanName 列,并且需要在其他查询中可以搜索,原因是如果我当前搜索“bob smith”我得到 0 个匹配项,但 bob 返回匹配项是因为名字,所以在这个例子中,cleanname 实际上是完整的姓名
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