如:
现有表:
T
字段:
ID S V
数据:
1 A 12
1 B 32
1 C 23
2 A 26
2 B 14
2 C 50
3 A 33
3 B 9
3 C 43
如何使用一语句查找:S=A,V>20;S=B,V>10;的记录?
因为查询条件是动态生成的,或者会出现S=C,S=D,S=E...等情况,
所以要求语句能灵活添加条件。
现有表:
T
字段:
ID S V
数据:
1 A 12
1 B 32
1 C 23
2 A 26
2 B 14
2 C 50
3 A 33
3 B 9
3 C 43
如何使用一语句查找:S=A,V>20;S=B,V>10;的记录?
因为查询条件是动态生成的,或者会出现S=C,S=D,S=E...等情况,
所以要求语句能灵活添加条件。
解决方案 »
- 如何建立一个ms Server 数据库的用户,它只能读视图?
- 表结构转换
- 我也有个sql语句不会写,希望大家帮忙?
- mssql 视图数据是什么时候产生的啊
- 再问一个问题~~谁能帮下~生成视图的~很简单~帮下忙~谢谢
- sql server profiler连接问题
- 请教高手:这个SQLSERVER存储过程怎么设计效率高?
- 问个数据更新的问题
- 看看我写的存储过程有没有错误?
- 高手请进!
- select top 50 convert(varchar(19),SAMPLING_DATETIME,121) as SAMPLING_DATETIME, * from table 这个查询语句我想要这样的结果
- 服务器迁移引起的SQL登陆名问题!
go
insert into T
select 1,'A',12
union all select 1,'B',32
union all select 1,'C',23
union all select 2,'A',26
union all select 2,'B',14
union all select 2,'C',50
union all select 3,'A',33
union all select 3,'B',9
union all select 3,'C',43
go
create procedure p_t(@cond varchar(100))
as
declare @sql varchar(1000)
set @sql='select * from t where '+@cond
exec(@sql)
go
select * from T
go
exec p_t 'S=''A'' and V>20'
go
drop table T
drop proc p_t
(9 行受影响)
ID S V
----------- ---------- -----------
1 A 12
1 B 32
1 C 23
2 A 26
2 B 14
2 C 50
3 A 33
3 B 9
3 C 43(9 行受影响)ID S V
----------- ---------- -----------
2 A 26
3 A 33(2 行受影响)
create procedure p_t(@cond varchar(100))
as
declare @sql varchar(1000)
set @sql='select * from t where '+@cond
exec(@sql)go
--如果楼主的条件都是S=?,V>?,则可以这样
create procedure p_t2(@S varchar(10),@V int)
as
declare @sql varchar(1000)
set @sql='select * from t where S='''+@S+ ''' and V>'+cast(@v as varchar)
exec(@sql)goexec p_t 'S=''A'' and V>20'
exec p_t2 'B',10
go
ID S V
----------- ---------- -----------
2 A 26
3 A 33(2 行受影响)ID S V
----------- ---------- -----------
1 B 32
2 B 14(2 行受影响)
as
declare @sql varchar(1000)
set @sql='select * from t where '+@cond
exec(@sql)go
--如果楼主的条件都是S=?,V>?,则可以这样
create procedure p_t2(@S varchar(10),@V int) --@S,@V也是存储过程的参数,分别对应对应字段S以及V,这个存储过程只适用于S字段的值用=比较,V字段的值用>比较的情况.
as
declare @sql varchar(1000)
set @sql='select * from t where S='''+@S+ ''' and V>'+cast(@v as varchar)
exec(@sql)goexec p_t 'S=''A'' and V>20'
exec p_t2 'B',10
go
exec p_t 'S=''A'' and V>20' --执行存储过程,取s='a'且v>20的记录
exec p_t2 'B',10 --执行存储过程,取s='b'且v>10的记录
as
declare @sql varchar(1000)
set @sql='select * from t where '+@cond
exec(@sql)
可以自己随意的输入条件,如exec p_t '(S=''A'' and V>20) or (S=''A'' and V>20)'
--结果
ID S V
----------- ---------- -----------
1 B 32
2 A 26
2 B 14
3 A 33
我想要的是符合条件的记录的ID。如:
我要查找(S=A,V>20) and (S=B,V>10)
我要得到的结果是
ID=2;
and id in(select id from T where S='B' and V>10)
as
declare @sql varchar(1000)
set @sql='select distinct id from T where id in(select id from t where '+@cond1+') and id in(select id from T where '+@cond2+')'
exec(@sql)
go
exec p_t 'S=''A'' and V>20','S=''B'' and V>10'--结果
id
-----------
2(1 行受影响)