Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

XP_SENDMAIL and Passing Query Parameters

Posted on 2004-09-27
2
Medium Priority
?
503 Views
Last Modified: 2010-10-11
Hi,

I have the following in a sp:

select @query_email= 'select column_1, column_2 from my_table where column_1='@parameter''
EXEC master.dbo.xp_sendmail @recipients = @email,
   @query = @query_email

The @parameter is defined earlier (correctly and also the @email too).

How can I run the query in xp_sendmail and also pass a parameter from the sp into the query?

Thanks,

Farawayman
0
Comment
Question by:farawayman
2 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 2000 total points
ID: 12160105
You have to put the parameter VALUE inside the @query string, because xp_sendmail won't know about it otherwise:
select @query_email= 'select column_1, column_2 from my_table where column_1=''' + @parameter + ''''

Please take care that the @parameter value is "secure", so that it cannot contain malicious code.
To be sure the above works also if @parameter contains a ' in it (like Mc'Donald for names), use this

select @query_email= 'select column_1, column_2 from my_table where column_1=''' + replace(@parameter, '''', '''''') + ''''

CHeers
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ready to get certified? Check out some courses that help you prepare for third-party exams.
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

927 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question