日期:2014-05-18  浏览次数:20480 次

用存储过程实现搜索功能,前提:未知表名,未知条件。
用存储过程实现搜索功能,前提:未知表名,未知条件。

------解决方案--------------------
SQL code
create proc procforsearch
@tablename varchar(30),
@wheresql  varchar(100)
as
declare @sql varchar(max)
declare @columns1 varchar(100)
declare @columns2 varchar(100)
declare @sql2 varchar(max)
declare @sql3 varchar(max)
declare @sql1 varchar(max)
set @sql=''
set @sql1=''
declare c_cur cursor
for select name  from syscolumns a where  exists(select 1 from sysobjects where name=@tablename and a.id=id)
open c_cur
fetch next from c_cur into @columns1
while @@fetch_status=0
begin
      set @sql=@sql+' or '+@columns1+' like ''%'+@wheresql+'%'' '
fetch next from c_cur into @columns1
end
close c_cur
deallocate c_cur
print @sql
set @sql=right(@sql,len(@sql)-3)
set @sql2='select * from '+@tablename+' where '+@sql+''
print @sql2
exec (@sql2)

exec procforsearch 'test1','1'