if 中的条件是动态SQL语句,该怎么写
比如:
if exists(select * from students where id in ( 'XD-102 ', 'XD-103 ', 'X-105 '))
print '满足条件 '
else
print '不满足条件 '
上面的if条件中的id值如果来自变量,该如何写???
我尝试这样写但提示语法错误:
declare @list varchar(8000),@sql varchar(8000)
set @list = ' ' 'XD-102 ' ', ' 'XD-103 ' ', ' 'X-105 ' ' '
set @sql = 'if exists(select * from students where id in ( '+@list+ ')) '
if exec(@sql)
print '满足条件 '
else
print '不满足条件 '
------解决方案----------------------改用CharIndex就可以不用動態SQL語句
declare @list varchar(8000),@sql varchar(8000)
set @list = 'XD-102,XD-103,X-105 '
if exists(select * from students where CharIndex(id, @list) > 0)
print '满足条件 '
else
print '不满足条件 '
------解决方案--------------------declare @list varchar(8000),@sql varchar(8000)
set @list = ' ' 'XD-102 ' ', ' 'XD-103 ' ', ' 'X-105 ' ' '
set @sql = 'select * from students where id in ( '+@list+ ') '
if exists(exec(@sql))
print '满足条件 '
else
print '不满足条件 '
------解决方案--------------------declare @list varchar(8000),@sql varchar(8000),@count int
set @list = ' ' 'XD-102 ' ', ' 'XD-103 ' ', ' 'X-105 ' ' '
set @sql = 'select * from students where id in ( '+@list+ ') '
exec sp_executesql @sql
set @count=@@rowcount
if(@count> 0)
print '满足条件 '
else
print '不满足条件 '
------解决方案--------------------declare @list varchar(8000),@sql varchar(8000)
set @list = ' ' 'XD-102 ' ', ' 'XD-103 ' ', ' 'X-105 ' ' '
set @sql = 'select * from students where id in ( '+@list+ ') '
if @@ROWCOUNT> 0
print '满足条件 '
else
print '不满足条件 '
------解决方案--------------------在跟踪器里跟踪下,就可以看到为什么不能用in了
------解决方案--------------------declare @list varchar(8000)
set @list = ' ' 'XD-102 ' ', ' 'XD-103 ' ', ' 'X-105 ' ' '
if exists(select 1 from student where charindex( ', '+id+ ', ', ', '+@list+ ', ')> 0)
print '满足条件 '
else
print '不满足条件 '