sp_executesql参数传递问题

jiaai 2010-03-23 09:24:03
exec sp_executesql N'select * from l_goodsbom where goodsid=3935 and (charindex(@P1,rtrim(ltrim(memo)))<>0 or charindex(@P2,rtrim(ltrim(memo)))<>0)', N'@P1 varchar(128),@P2 varchar(128)', '''BD1替代料''', '''BD1 替代料'''
执行查询不到结果,而下面的语句可以查询到结果,请各位指点一下,谢谢
exec sp_executesql N'select * from l_goodsbom where goodsid=3935 and (charindex(''BD1替代料'',rtrim(ltrim(memo)))<>0 or charindex(''BD1 替代料'',rtrim(ltrim(memo)))<>0)'
...全文
168 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jiaai 2010-03-23
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 chinajiabing 的回复:]
SQL code

--try

exec sp_executesql N'select * from l_goodsbom where goodsid=3935 and (charindex(@P1,rtrim(ltrim(memo)))<>0 or charindex(@P2,rtrim(ltrim(memo)))<>0)',
N'@P1 varchar(128),@P2 var……
[/Quote]

还是不能查询到时结果
ChinaJiaBing 2010-03-23
  • 打赏
  • 举报
回复

--try

exec sp_executesql N'select * from l_goodsbom where goodsid=3935 and (charindex(@P1,rtrim(ltrim(memo)))<>0 or charindex(@P2,rtrim(ltrim(memo)))<>0)',
N'@P1 varchar(128),@P2 varchar(128)','@p1=''BD1替代料''', '@p2=''BD1 替代料'''
Mr_Nice 2010-03-23
  • 打赏
  • 举报
回复
前者,语法不对吧!
jiaai 2010-03-23
  • 打赏
  • 举报
回复
但是为什么后一条能查询到结果,前一条不能,还请指点
dawugui 2010-03-23
  • 打赏
  • 举报
回复
如果是对引号存在疑问,则参考如下:

--动态sql语句基本语法
 
1 :普通SQL语句可以用Exec执行

eg: Select * from tableName
Exec('select * from tableName')
Exec sp_executesql N'select * from tableName' -- 请注意字符串前一定要加N

2:字段名,表名,数据库名之类作为变量时,必须用动态SQL

eg:
declare @fname varchar(20)
set @fname = 'FiledName'
Select @fname from tableName -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。
Exec('select ' + @fname + ' from tableName') -- 请注意 加号前后的 单引号的边上加空格

当然将字符串改成变量的形式也可
declare @fname varchar(20)
set @fname = 'FiledName' --设置字段名

declare @s varchar(1000)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句会报错

declare @s Nvarchar(1000) -- 注意此处改为nvarchar(1000)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句正确

3. 输出参数
declare @num int,
@sqls nvarchar(4000)
set @sqls='select count(*) from tableName'
exec(@sqls)
--如何将exec执行结果放入变量中?

declare @num int,
@sqls nvarchar(4000)
set @sqls='select @a=count(*) from tableName '
exec sp_executesql @sqls,N'@a int output',@num output
select @num
bancxc 2010-03-23
  • 打赏
  • 举报
回复
看看 为什么不直接用2呢
dawugui 2010-03-23
  • 打赏
  • 举报
回复
一个是用变量查询,一个是用常量查询,两个等价.
永生天地 2010-03-23
  • 打赏
  • 举报
回复
占个座 看

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧