在公司项目中,需要用到一个方法,就是批量传入记录编号 通过 where jlbh in()的方法查询记录;
平时直接用 select * from JDZS where Jlbh in(‘001’,‘002’,‘003’) 完全没有问题。
但是我在用到的Fastreport报表插件中,会使用参数传入查询条件来执行SQL语句,原SQL语句“select Jlbh from JDZS where Jlbh in(''+@jlbhStr+'')”加上参数就变成:
exec sp_executesql N'select * from JDZS where Jlbh in(@Jlbh)',N'@Jlbh nvarchar(50)',@Jlbh='2018090701016'
以上方法中,如果参数@Jlbh 传入多个记录编号,就会出现查询无结果。
通过以下几种方法都试过,要么无结果,要么参数中只能传入一个记录编号,要么就在FastRepot中报错;
--方法一
exec sp_executesql N'select Jlbh as 记录编号,QbBh as 气表编号 from JDZS where Jlbh in (''+@jlbhStr+'')',N'@jlbhStr varchar(95)',@jlbhStr='''2018090701016'''
--方法二
exec sp_executesql N'exec(''select Jlbh from JDZS where Jlbh in(''''''+@jlbhStr+'''''')'')',N'@jlbhStr nvarchar(4000)',@jlbhStr=N'2018090701016'
--方法三
exec sp_executesql N'exec(''select Jlbh from JDZS where Jlbh in(''''+@jlbhStr+'''')'')',N'@jlbhStr nvarchar(4000)',@jlbhStr=N'''2018090701016'''
--方法四
exec sp_executesql N'exec(''select * from JDZS where Jlbh in(''+@jlbhStr+'')'')',N'@jlbhStr nvarchar(4000)',@jlbhStr=N'''2018090701016'',''2018090701015'''
--只有方法四能够执行成功,但是把其中的exec(''select * from JDZS where Jlbh in(''+@jlbhStr+'')'') 放入 FastReport中要报错;
网上找了一篇相似的问题:
同时按照这个方法执行后还是查询无结果。
但是看到最终的答案就是相当于把第一个回答中的内容改变了方式执行。于是就想到了替换的方式。既然
exec('select Jlbh from JDZS where Jlbh in('+@jlbhStr+')') 是能够被执行的。那就把这句话放入sp_executesql 中执行,把单引号部分用双引号替换一下。
最终exec 执行的语句就是:
--通过exec declare变量方法执行是可行的;
declare @sqlids NVARCHAR(4000)
set @sqlids='''2018090701016'',''2018090701015'''
exec('select * from JDZS where Jlbh in (' + @sqlids + ')')
--将sp_executesql 中可执行的sql查询语句
exec sp_executesql N'exec(''select * from JDZS where Jlbh in(''+@jlbhStr+'')'')',N'@jlbhStr nvarchar(4000)',@jlbhStr=N'''2018090701016'',''2018090701015'''
--替换为 执行exec体:
exec sp_executesql N' declare @sqlids NVARCHAR(4000)
set @sqlids=@jlbhStr
exec(''select * from JDZS where Jlbh in ('' + @sqlids + '')'')',N'@jlbhStr nvarchar(4000)',@jlbhStr=N'''2018090701013'',''2018090701012'''
当执行参数 @jlbhStr=N'''2018090701016'',''2018090701015''' 的时候就可以查询出想要的结果;而我最终要的就是sp_executesql(' ')中的部分,
所以最终的语句就是把原来的“ select Jlbh from JDZS where Jlbh in(''+@jlbhStr+'')” 替换为:
declare @sqlids NVARCHAR(4000)
set @sqlids=@jlbhStr
exec('select * from JDZS where Jlbh in (' + @sqlids + ')')
实际传入的参数变量的字符按照平时SQL中的 where in方法即可:set @jlbhStr='''2018090701016'',''2018090701015''';