模糊查询的通用存储过程
程序员文章站
2023-12-04 17:42:10
复制代码 代码如下:if exists(select 1 from sysobjects where name='sp_search' and xtype='p') dro...
复制代码 代码如下:
if exists(select 1 from sysobjects where name='sp_search' and xtype='p')
drop procedure sp_search
go
/*
模糊查询的通用存储过程
create by sxm,date 2009-7-14
参数:
@table_name 表名
@condition 条件
*/
create proc sp_search(@table_name varchar(200),@condition varchar(100))
with encryption
as
begin
declare @strsql varchar(8000)
declare @col_name varchar(100)
declare @str_cols varchar(8000)
set @str_cols=''
--查询表中的列名
declare cur_1 cursor for select column_name from information_schema.columns where table_name=@table_name
open cur_1
fetch cur_1 into @col_name
while @@fetch_status=0
begin
--组合查询条件
set @str_cols=@str_cols + @col_name+' like ''%' + @condition+ '%''' + ' or '
fetch cur_1 into @col_name
end --while
close cur_1
deallocate cur_1
set @str_cols=left(@str_cols,len(@str_cols)-3)
--print @str_cols
set @strsql='select * from '+@table_name+' where '+ @str_cols
exec(@strsql)
end