一个存储过程引发的错误,急!帮忙看一下
CREATE procedure [dbo].[build_mail] @gsid bigint,@mname varchar(100),@topic varchar(250),@msg varchar(100),@sql ntext
as
declare @id int
begin tran
select @id=isnull(max(id),0) from mission
set @id=@id+1
insert into mission(accid,missionname,title,[message],sort) values(@gsid,@mname,@topic,@msg, 'mail ')
exec( 'insert into mission_list(misid,target) select '+@id+ ',* from ( '+@sql+ ') aa ')
commit tran
以上是存储过程,传递4个参数,最后一个是SQL语句,下面是执行过程:
build_mail 580, '580_mail_20074325 ', '23423 ', '369 ',SELECT userlist.Email FROM userlist INNER JOIN qyml ON Qyml.ID = userlist.gsid where ( (qyml.sf= '广东 ' and qyml.city = '广州 ')) and (( qyml.hylb like '%贸易型-板材类-热轧板卷% ')) group by userlist.email
在查询分析器检查,出现一下错误:
消息 103,级别 15,状态 4,第 1 行
以 'SELECT userlist.Email FROM userlist INNER JOIN qyml ON Qyml.ID = userlist.gsid where ( (qyml.sf= '广东 ' and qyml.city = '广州 ')) and ( ' 开头的 标识符 太长。最大长度为 128。
还有就是sql语句有 " ' "符号,怎么处理才能不出错?
------解决方案--------------------两个单引号代表一个单引号
------解决方案--------------------build_mail 580, '580_mail_20074325 ', '23423 ', '369 ',SELECT userlist.Email FROM userlist INNER JOIN qyml ON Qyml.ID = userlist.gsid where ( (qyml.sf= '广东 ' and qyml.city = '广州 ')) and (( qyml.hylb like '%贸易型-板材类-热轧板卷% ')) group by userlist.email
改為
EXEC build_mail 580, '580_mail_20074325 ', '23423 ', '369 ', 'SELECT userlist.Email FROM userlist INNER JOIN qyml ON Qyml.ID = userlist.gsid where ( (qyml.sf= ' '广东 ' ' and qyml.city = ' '广州 ' ')) and (( qyml.hylb like ' '%贸易型-板材类-热轧板卷% ' ')) group by userlist.email '
------解决方案--------------------1.@sql ntext===> @sql varchar(8000)
2. 'insert into mission_list(misid,target) select '+@id+ ',* from ( '+@sql+ ') aa '
===> 'insert into mission_list(misid,target) select '+ltrim(@id)+ ',* from ( '+@sql+ ') aa '
3.同上