按条件查询某个表中某些字段的值(精确查询)
create proc selectOfCondition_someColumn_allRecord_proc
@tableName varchar(100), --要查询的表名
@column nvarchar(2000), --要查询的字段名组成的字符串,(字段名之间用','隔开)
@condition nvarchar(2000), --查询条件的字段名组成的字符串,(字段名之间用','隔开)
@value nvarchar(2000) --查询条件的值组成的字符串,(值之间用','隔开)
as
begin
declare @i int; --保存控制循环条件(取得的字段名中'的位置)的变量
declare @j int; --保存取得的字段取值中'的位置
declare @sql nvarchar(4000); --保存查询语句的字符串
declare @count int; --保存参数总数的变量
declare @tableId int; --保存表的ID的变量
declare @coulmnCount int; --保存字段的ID的变量
declare @countSet int; --保存查询结果的记录总数
select @tableId=id from sysobjects where name=@tableName; --查询表的ID
if(@tableId !=0)
begin --如果有这个表
set @sql=N' select '+@column+N' from '+@tableName+N' where ';
set @count=0;
set @i=charindex(',',@condition); --取出第一个字段名中的'
set @j=charindex(',',@value); --取出第一个字段值中的'
while @i!=0
begin
select @coulmnCount=count(*) from syscolumns where name=left(@condition,@i -1) and id=@tableId
if(@coulmnCount!=0) --如果有这个字段
begin
set @sql=@sql+left(@condition,@i -1)+N' ='''+left(@value,@j -1)+''''+N' and ';
set @condition=right(@condition,len(@condition)-charindex(',',@condition));
set @value=right(@value,len(@value)-charindex(',',@value));
set @i=charindex(',',@condition);
set @j=charindex(',',@value);
set @count=@count+1;
end
else --如果没有这个字段
return @count+1 --则返回这个字段的位置
end
select @coulmnCount=count(*) from syscolumns where name=@condition and id=@tableId
if(@coulmnCount!=0) --如果存在最后一个字段
begin
set @sql=@sql+@condition+N' ='''+@value+''''
set @count=@count+1;
exec sp_executesql @sql; --查询记录
return 0; --成功执行存储过程
end
else --没果不存在最后一个字段
return @count+1 --则返回这个字段的位置
end
else
return -1 --没有这个表
end
go