按条件查询某个表中某些字段的值(精确查询)的通用存储过程

按条件查询某个表中某些字段的值(精确查询)
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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值