2012-05-30 3 views
0

전자 메일을받는 사람 목록에 개별적으로 보내려고합니다. 나는 오류가 발생하고있다 :sp_send_dbmail에서 변수를 사용하여 쿼리를 실행할 때 오류가 발생했습니다.

여기
Msg 22050, Level 16, State 1, Line 0 
Error formatting query, probably invalid parameters 
Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 478 
Query execution failed: Msg 4104, Level 16, State 1, Server xxxxxx, Line 1 
The multi-part identifier "[email protected]" could not be bound. 

내 코드의 단순화 된 버전입니다, 표를 asssuming 것은 유효한 기존 테이블 이름과 이메일 기존하는 열입니다.

declare @current_mailaddress varchar(50), @query varchar(1000) 
set @current_mailaddress = '[email protected]' 

set @query = 'select distinct name, email from table1 
       where email = ' + @current_email 

exec msdb.dbo.sp_send_dbmail 
@recipients = @current_email, 
@subject = 'test', 
@query = @query 

그래서 오류에 따르면 서식 지정 (아마도 @query)이 잘못되었습니다. 나는 그것을 이해할 수 없다. 어떤 아이디어?

답변

2

당신은 따옴표로 @current_email의 값을 넣어해야합니다

'SELECT ... WHERE email = ''' + @current_email + '''' 

가 확인하려면 왜 쿼리는 현재이없는 모양을 고려 :

SELECT ... WHERE email = [email protected] 

동적 SQL 작업을 모든 시간을 이상한 오류가 발생하면 디버깅을 위해 변수를 PRINT하는 것이 좋습니다. 일반적으로 작성한 SQL 문자열이 예상 한 문자열이 아닙니다. 관련없는 다른 answer에서 디버깅 코드를 관리하는 쉬운 방법을 제안했습니다.

관련 문제