可在任何一个表(或视图)中按任何一个字段值进行查询的存储过程(精确查询)
create proc allTable_selectOfOne_proc
@tableName nvarchar(500), --表名或视图名
@condition nvarchar(500), --字段名(如果是all,则表示查询某个表中所有的记录)
@value nvarchar(500) --字段值
as
begin
declare @sql nvarchar(500); --保存查询sql语句字符串
declare @tableId int; --保存表的ID的变量
declare @coulmnCount int; --保存字段的ID的变量
declare @count int; --保存查询结果的记录总数
set @tableId=0;
set @coulmnCount=0;
set @count=-1;
select @tableId=id from sysobjects where name=@tableName; --查询表的ID
if(@tableId !=0) --如果有这个表
if(@condition!='all') --如果不是要查询所有的记录
begin
select @coulmnCount=count(*) from syscolumns where name=@condition and id=@tableId
if(@coulmnCount!=0) --如果有这个字段
begin
set @sql=N'select * from '+@tableName +N' where '+@condition+N'= '''+@value+'''';
exec sp_executesql @sql; --查询记录
set @count=@@rowcount;
if(@count >0) --如果有记录
begin
return 0; --有记录
end
else
return 3; --没有记录
end
else
return 2 --没有这个字段
end
else --如果是要查询所有的记录
begin
declare @sqlAllInfo nvarchar(500);
set @sqlAllInfo=N'select *from '+@tableName;
exec sp_executesql @sqlAllInfo;
set @count=@@rowcount;
if(@count >0) --如果有记录
begin
return 0; --有记录
end
else
return 3; --没有记录
end
else
return 1 --没有这个表
end
GO