存储过程中有一参数@no,其值是 '001’,'002' 的形式。而存储过程的查询大概是这样:
select * from Tab where No in ('001','002')
试过select * from Tab where No in (@no),不可行。
现在使用把SQL语句写成字符串@sql,然后是exec(@sql) 。
请问使用这种方法是否比在存储过程直接使用SQL语句查询的慢?如果想要直接查询 select * from Tab where No in ,in后面怎么写?
select * from Tab where No in ('001','002')
试过select * from Tab where No in (@no),不可行。
现在使用把SQL语句写成字符串@sql,然后是exec(@sql) 。
请问使用这种方法是否比在存储过程直接使用SQL语句查询的慢?如果想要直接查询 select * from Tab where No in ,in后面怎么写?
你要不就使用sp_executesql
declare @sql nvarchar(2000),@no nvarchar(200)
select @sql =' select * from Tab where No in ( ' ,@no ='''001'',''002'''
select @sql = @sql +@no + ')'
exec sp_executesql @sql
-----------
这个可以重用执行计划,
应该来说多次执行要快点~
那就貌似没有什么好的方式了..
但是 直接SQL语句还需要经过这些步骤
显然存储过程花费的时间要短建议使用存储过程实现
set @s='001,002'
select * from Tab
where charindex(','+ltrim(No)+',',','+@s+',')>0
if object_id('Tab') is not null
drop table Tab
go
create table Tab
( No int,
姓名 nvarchar(10)
)
insert into Tab select 001,'张三'
union all select 002,'李四'
go
declare @No nvarchar(3)
set @No=001
select * from Tab where No in ('001','002')
select * from Tab where No in (@no)
if object_id('Tab') is not null
drop table Tab
go
create table Tab
( No nvarchar(6),
姓名 nvarchar(10)
)
insert into Tab select 001,'张三'
union all select 002,'李四'
go
declare @sql nvarchar(100),@No nvarchar(10)
set @sql='select *from Tab where No in('
set @No='001,002'
select * from Tab where No in (001,002)
set @sql=@sql+@no +')'
exec sp_executesql @sql
set @No='张三,李四'select tab.* from Tab ,#
where charindex((tab.姓名),@No)=#.px