--获得type所对应的id create by youhaoxinqin 2014-7-8 13:54
create table typeid(
id int identity(1,1),
type int
)
--初始化数据
insert into typeid(type) values(1)
insert into typeid(type) values(1)
insert into typeid(type) values(2)
insert into typeid(type) values(1)
insert into typeid(type) values(3)
insert into typeid(type) values(2)
insert into typeid(type) values(3)
select * from typeid
--创建全局临时表
create table ##remmber_type_id(
type int,
id nvarchar(200)
)
--创建游标
declare type_id_cursor cursor for select * from typeid
go
open type_id_cursor
declare @cursor_id int
declare @cursor_type int
declare @cursor_count int
declare @original_id nvarchar(200)
fetch next from type_id_cursor into @cursor_id,@cursor_type
while @@fetch_status=0
begin
select @cursor_count=count(*) from ##remmber_type_id where type=@cursor_type
if(@cursor_count>0)
begin
select @original_id=id from ##remmber_type_id where type=@cursor_type
update ##remmber_type_id set id=( @original_id+','+cast(@cursor_id as nvarchar(200))) where type=@cursor_type
end
if(@cursor_count=0)
begin
insert into ##remmber_type_id(type,id) values(@cursor_type,cast(@cursor_id as nvarchar(200)))
end
fetch next from type_id_cursor into @cursor_id,@cursor_type
end
close type_id_cursor
deallocate type_id_cursor
--检索数据
select * from ##remmber_type_id
---丢弃临时表
drop table ##remmber_type_id
第一种写法是正确的。
当然你如果条件多了,还可以加()
如:
select * from tb where (a字段='x' or a字段='y') and b字段='zzz'
简单的SQL是做不到你这样的要求的,这个得用游标,
跟你从客户端取出来遍历数据集是一个意思
介绍sql语句如何使用函数