select a from 表名 where c=某值这样会得到一个结果集。将结果集放在datareader中,然后通过datareader不就可以一条记录一条记录的处理了吗?如果说,你想完全通过SQL来做的话。 你说一个“需要用A的值到另外的表去查询数据”的具体需求吧。因为给定一个C,可能得到多个A值。 你想如果处理这些A值?
create table ta(A int, B int, C varchar(10)) go insert ta select 7, 3, 'a' union all select 2, 5, 'a' union all select 9, 6, 'a' union all select 4, 7, 'b' union all select 5, 8, 'b' union all select 6, 3, 'c' /*方法一: 通过字符串模拟数组。 将想要的值,以某个不会在数据中出现的间隔符,串联起来。 使用时,再切分 */ declare @str varchar(8000) set @str='' select @str=@str+convert(varchar(10), a)+'@' from ta where c='a' select @str /*方法二: 用一个带有序号列的临时表或表变量 */ declare @t table(id int identity(1, 1),A int, B int, C varchar(10)) insert @t select * from ta select * from @t where c='a' --清除 drop table ta
你说一个“需要用A的值到另外的表去查询数据”的具体需求吧。因为给定一个C,可能得到多个A值。
你想如果处理这些A值?
而我在循环的时候获得A值总是所获得A值的第一个值,无法继续读到下一个值!
要完全通过SQL来做完全通过,不用游标,因为太慢而且容易造成死锁!
go
insert ta select 7, 3, 'a' union all select 2, 5, 'a'
union all select 9, 6, 'a' union all select 4, 7, 'b'
union all select 5, 8, 'b' union all select 6, 3, 'c'
/*方法一:
通过字符串模拟数组。
将想要的值,以某个不会在数据中出现的间隔符,串联起来。
使用时,再切分
*/
declare @str varchar(8000)
set @str=''
select @str=@str+convert(varchar(10), a)+'@'
from ta where c='a'
select @str
/*方法二:
用一个带有序号列的临时表或表变量
*/
declare @t table(id int identity(1, 1),A int, B int, C varchar(10))
insert @t select * from ta
select * from @t where c='a'
--清除
drop table ta
方法非常好!
测试已经可行了!
非常感谢!