Automatically Email Query Results

Aug 14, 2007



I'm very new to SQL but I have figured out how to do my first query. Now I would like to automate it to send the query as an attachment to users automatically (scheduler/cron??). How would you go about this, I need step by step hints. I'm using SQL Query Analyzer ver 8.00.2039 to generate the query from CDR records. Is this even possible?

Thank you for any guidance.

View 3 Replies


ADVERTISEMENT

Email The Results Of The Query

Apr 17, 2007

Hello,

I want to email the results of the query. The query output can be email either as the HTML body of the email to be sent or as a excel attachement.



I am wondering as to what would be the best way to achive this.

a) I could have a email client module in C# or VB.NET 2.0, which would fetch the query resultset and store it in a dataset. I format it as HTML body and send the email using System.NET. For excel, can use XSLT



Please suggest if there is any other approach that would be more suitable.



Thanks.

View 3 Replies View Related

Send Query Results Via Email

Sep 27, 2007

is it possible to use send mail task to send results of a query via email? if it can be sent then what would the result look like? will it be like excel type format or fixed length? or comma delimited?

and obviously -- how can I accomlish it?
thanks

View 5 Replies View Related

MS SQL 6.5 Procedure To Send Query Results Via Email

Jul 20, 2005

Hi,I'm not sure if this is possible as i've googled everywhere, but i have aselect query that returns a customer record with their associated salesorders. I would like to automate a process which sends an email reminder toeach customer in the database, that has outstanding orders. This emailreminder should have the results of the query regarding their account.The table structure are as follows.---------------------Customer_tbl---------------------CustomerIDAccountNoNameEmailAddress---------------------Order_tbl---------------------OrderIDCustomerIDReferenceAmountDateOutstanding_flgCan anyone help?Sen.

View 2 Replies View Related

Transact SQL :: Send Email Only If Query Contains Results

Aug 8, 2015

I’m running a data integrity procedure from an agent job that is a scheduled weekly maintenance task which emails the results of my query, and is working properly.

I would however like this to only receive the email it the query contains results, and not send it no records are found to prompt me to take action.
 
My code less the personal information
  
EXEC msdb.dbo.sp_send_dbmail     
@profile_name
= '',
       @recipients
= '',
       @subject
= 'Database Integrity - Import Errors',

[Code] ....

View 5 Replies View Related

Schedule And E-mail Query Results In HTML Formated Email

Aug 14, 2004

Could anyone walk me through how to do the following:

Schedule a query to run at a designated time
Embed the resulting table in a HTML email
Email the HTML formated results someone automatically


Can this be done with SQL Server only or is there a third party app?



I know its alot but I'm having a hard time finding resourses.

View 1 Replies View Related

Export Query Results To Excel File And Add As Attachment In Email

Jan 2, 2014

Is there a way to export query results to an excel fie and add that file as an attachment in the email? All this has to be done using SQL query and it needs to be automated. My coworker tried using Openrowset and BCP, but it is not working.

View 3 Replies View Related

SQL 2012 :: Possible To Send Pivot Query Results As Automated Database Email?

Nov 26, 2014

possible to send Pivot query results as automated database email ?

View 3 Replies View Related

Send An Email Alert Automatically?

Feb 29, 2004

When a new record is inserted into the database.
I want this to trigger an email that will be sent to all users who requested one when a new record was added.
I can't figure the best way to set this up.
All help gratefully received.
Thanks
JB

View 2 Replies View Related

How To Automatically Save Email Attachment

Feb 19, 2015

I get an email daily with an attachment. I want to automatically save the attachment to a server. I managed to get a rule on outlook to save the attachment in a folder on my computer. But I want it saved to a folder on a server. How can I do this?

View 4 Replies View Related

How To Send Email Automatically To Users From Table?

May 2, 2008

Hi,

First of all I want to apologize if I am in the wrong forum. I am new to SQL Server.
I have a table with a field containing email address from user input. Is there a build-in function or script in SQL Server 2005 that I can send a template of a email message to users? If not in what way can I acheive this?

Thanks for all your reply.

View 16 Replies View Related

Hi, Please Help Me W/ Fetch Cursor Querying, This Sends Email Automatically

Dec 18, 2007

create proc emailnew

as
declare @From varchar(8000)
declare @Subject varchar(8000)
declare @Body varchar(4000)
declare @smtp varchar(8000)
declare @counter int, @tbl varchar(8000)
Declare @MailID int
Declare @hr int
Declare @To varchar(8000)
Declare @tblquery varchar(8000)
declare @id int, @deptemail varchar(8000), @tmpmth varchar(8000), @usedb varchar(8000)
set @from = 'name@mail.com'
set @subject = 'testheader'
set @body = 'testing successful'
set @smtp = 'smtp.com'

--=========================================================================
--============================ get database name =======================
IF (LEN(MONTH(GETDATE())) = 1)
BEGIN
Set @TmpMth = '0' + CAST(MONTH(GETDATE()) AS varchar(2)) --01
END
ELSE
BEGIN
Set @TmpMth = CAST(MONTH(GETDATE()) AS varchar(2)) --12
END
SET @UseDB = 'DATA' + CAST(YEAR(GETDATE()) AS varchar(4)) + @TmpMth --aia_DATA200712
--===================================================================
--============================ get table number =======================
set @counter = 1
while @counter >= 59
begin
IF (LEN(@counter) = 1)
BEGIN
Set @Tbl = '0' + @counter --01
END
ELSE
BEGIN
Set @Tbl = @counter --12
END

--=========================check if table being created exists
IF EXISTS (SELECT 1
FROM information_schema.schemata
WHERE catalog_name = 'temptable')
GOTO table_1
--=================================== get all email accounts =====================
set @tblquery = '
select ID, Email
INTO temptable
FROM
(
select distinct d.id, d.email from tt32_aia.dbo.department d right outer join tt32_aia.dbo.extension e ON (e.parentid = d.id) right outer join
' + @usedb + '.dbo.other' + @tbl + ' data ON (e.extn = data.extn) where callclass = '''' or callclass is null
UNION ALL select distinct d.id, d.email from tt32_aia.dbo.department d right outer join tt32_aia.dbo.extension e ON (e.parentid = d.id) right outer join
' + @usedb + '.dbo.inward' + @tbl + ' data ON (e.extn = data.extn) where callclass = '''' or callclass is null
UNION ALL select distinct d.id, d.email from tt32_aia.dbo.department d right outer join tt32_aia.dbo.extension e ON (e.parentid = d.id) right outer join
' + @usedb + '.dbo.local' + @tbl + ' data ON (e.extn = data.extn) where callclass = '''' or callclass is null
UNION ALL select distinct d.id, d.email from tt32_aia.dbo.department d right outer join tt32_aia.dbo.extension e ON (e.parentid = d.id) right outer join
' + @usedb + '.dbo.other' + @tbl + ' data ON (e.extn = data.extn) where callclass = '''' or callclass is null
)data
DECLARE deptemail_cursor CURSOR FOR select id, email
from temptable where id is not null
'

--=============================================================================
--====just above you can see the cursor.. below is sending the emails
--======================================================================

exec(@tblquery)


OPEN deptemail_cursor


FETCH NEXT FROM deptemail_cursor INTO @id, @deptemail

WHILE @@FETCH_STATUS = 0
BEGIN
--If LEN(@deptemail) > 0
--BEGIN
set @to = @deptemail
EXEC @hr = sp_OACreate 'CDo.message', @MailID OUT --CDo.message |CDONTS.NewMail <-- different mail server
EXEC @hr = sp_OASetProperty @MailID ,
'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2'
EXEC @hr = sp_OASetProperty @MailID ,
'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', @smtp
EXEC @hr = sp_OASetProperty @MailID , 'From', @From
EXEC @hr = sp_OASetProperty @MailID , 'HTMLBody', @Body
EXEC @hr = sp_OASetProperty @MailID , 'Subject', @Subject
EXEC @hr = sp_OASetProperty @MailID , 'To', @to
EXEC @hr = sp_OAMethod @MailID , 'Send', NULL
EXEC @hr = sp_OADestroy @MailID
--END
FETCH NEXT FROM deptemail_cursor INTO @id, @deptemail
END

CLOSE deptemail_cursor
DEALLOCATE deptemail_cursor

Table_1:
drop table temptable
return


set @counter = @counter + 1

end




this is suppose to send email automatically to every email account that it will get from all the tables (around 250 tables).
the problem is its not sending, but if i try to take my code outside of the "SET @COUNTER = @COUNTER + 1 END" and close the if statement above, i can produce the correct result.. i'm thinking maybe its the positioning? but, there could be some overhauling needed to do with this.. sorry for posting the sp. sorry for the trouble.. please help me

View 2 Replies View Related

Do QA Results Into A Temp Table Automatically?

Apr 3, 2008

Does anyone know if the results from a query run in QA automatically go into a tempoary table? For instance if ive just run a query that took 5 minutes but it was a normal select query and after it ran i realised i wanted to query the results could i run a simple command to mke a copy of the result set rather than run the original query into a temp table that would then take a few minutes again?

View 1 Replies View Related

Getting Results In An EMail PDF?

Aug 21, 2007

We have the following proc that executes an e-mail and attaches the resulting query as a TXT attachment. Is there a way to make the attachment be a PDF?


@MYRECIPIENTS varchar (500)

, @MYSUBJECT varchar (50)

, @MYBODY varchar (500)

, @MYQUERY varchar (1000)

, @MYIMPORTANCE varchar (10)

, @MYPROFILE varchar (50)

as

declare @NewSubject varchar(200)

set @NewSubject = @MYSUBJECT + ' ' + Cast(GetDate() as varchar(20))

Execute msdb.dbo.sp_send_dbmail

@profile_name = @MYPROFILE

,@recipients = @MYRECIPIENTS

,@subject = @NewSubject

,@body = @MYBODY

,@query = @MYQUERY

,@importance = @MYIMPORTANCE

,@attach_query_result_as_file = 1

,@body_format = 'HTML'

View 3 Replies View Related

Email Job Output Results

Apr 14, 2008

Hi,

I was wondering is there was is a way in SQL 2005 to not only email job completion notifications but also include the output of a step (e.g. TSQL step) within the email. I was able to accomplish this in the past with SQL 2000 by writing output to a file and then adding an extra CMDEXEC step that exectuted BLAT (CLI SMTP engine) that sent the contents of the output file as email body out of band. Although this worked and I can do the same with 2005 it is not very elegant and I was wondering if 2005 version might have something built-in.

Any thoughts?

Thank you,


-Ed

View 1 Replies View Related

Send Per Email SELECT Results With More Than 1 Row

Nov 20, 2014

"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression"..It is about a Stored Procedure, which not only should output the number of opportunities with status "Pending" or "Accepted" but also the name of the opportunities with these statuses. Following points:

1. The SELECT that outputs the names of the opportunities may in some cases return more than one value. I created then the CURSOR CUR_TEST.

2. The code should return the names of Opportunities, namely after "The opportunities are:" and these must be sent to the recipients of an email. How can I do this, so the Names of the Opportunities and the rest of the email can be sent by email?. I mean, the concatenation with SET or SELECT doesn't work. I get as email only the output of the last row of the SELECT with cursor CUR_TEST.

3. I add an example how the output should be.

The following is the code:

BEGIN

declare
@V_USER VARCHAR(20),
@V_NAME VARCHAR(100),
@V_QUANTITY INT,
@V_EMAIL VARCHAR(60),
@V_BODY VARCHAR(MAX),
@V_QUANTITY_ACTIVE int,

[code]...

An example how the Output in the email body should be:

Dear MyName,
You have 47 Opportunities with status Pending.
The Opportunities are:

Name of Opportunity 1
Name of Opportunity 2
Name of Opportunity 3

View 1 Replies View Related

Sending Results Of Import Via Email

Nov 12, 2007

When I used the following code:

Imports System
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net.Mail
Imports System.Net
Imports System.Data
Imports System.IO
Imports Microsoft.SqlServer.Dts.Pipeline
Imports System.Text

Public Class ScriptMain
Public Sub Main()
Dim msg As MailMessage
Dim smtp As SmtpClient

Dim dt As Data.tbl_clients
Dim ad As New Data.OleDb.OleDbDataAdapter
dt = New System.Data.tbl_clients
ad.Fill(dt, Dts.Variables("User::AllFilesFound").Value)

Dim data As String

For Each row As Data.DataRow In dt.Rows
For Each column As Data.DataColumn In dt.Columns
data = data & (column.StaffNo & " : " & row(column.Ordinal).ToString()) & "<br>"
Next
Next

Dim sendNotify As String
sendNotify = "<pre>Cards to be printed " & Today() & " : <br><br>" & data.ToString() & ""

msg = New MailMessage( _
"my email", _
"my email again", _
"Subject: Cards to be printed", sendNotify)
smtp = New SmtpClient("smtp client")
smtp.Credentials = CredentialCache.DefaultNetworkCredentials
msg.IsBodyHtml = True
smtp.Send(msg)
Dts.TaskResult = Dts.Results.Success
End Sub
End Class

I got the following error:
The query failed to parse. An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name.

I would like to send an email notification after data has been imported into the table. Any response will be highly appreciated.

Many thanks,

Rupa

View 4 Replies View Related

Is There A Way To Hold The Results Of A Select Query Then Operate On The Results And Changes Will Be Reflected On The Actual Data?

Apr 1, 2007

hi,  like, if i need to do delete some items with the id = 10000 then also need to update on the remaining items on the with the same idthen i will need to go through all the records to fetch the items with the same id right?  so, is there something that i can use to hold those records so that i can do the delete and update just on those records  and don't need to query twice? or is there a way to do that in one go ?thanks in advance! 

View 1 Replies View Related

Need To Display Results Of A Query, Then Use A Drop Down List To Filter The Results.

Feb 12, 2008

Hello. I currently have a website that has a table on one webpage. When a record is clicked, the primary key of that record is transfered in the query string to another page and fed into an sql statement. In this case its selecting a project on the first page, and displaying all the scripts for that project on another page. I also have an additional dropdownlist on the second page that i use to filter the scripts by an attribute called 'testdomain'. At present this works to an extent. When i click a project, i am navigated to the scripts page which is empty except for the dropdownlist. i then select a 'testdomain' from the dropdownlist and the page populates with scripts (formview) for the particular test domain. what i would like is for all the scripts to be displayed using the formview in the first instance when the user arrives at the second page. from there, they can then filter the scripts using the dropdownlist.
My current SQL statement is as follows.
SelectCommand="SELECT * FROM [TestScript] WHERE (([ProjectID] = @ProjectID) AND ([TestDomain] = @TestDomain))"
So what is happening is when testdomain = a null value, it does not select any scripts. Is there a way i can achieve the behaivour of the page as i outlined above? Any help would be appreciated.
Thanks,
James.

View 1 Replies View Related

Transact SQL :: Create Email Report Which Gives Result Of Multiple Results From Multiple Databases In Table Format

Jul 24, 2015

I'm trying to create an email report which gives a result of multiple results from multiple databases in a table format bt I'm trying to find out if there is a simple format I can use.Here is what I've done so far but I'm having troble getting into html and also with the database column:

EXEC msdb.dbo.sp_send_dbmail
@subject
= 'Job Summary', 
@profile_name  =
'SQL SMTP',
   
[code]....

View 3 Replies View Related

Printing The Query Name Automatically

Oct 1, 2007

I'm trying to print my query name with my results. I know I can use PRINT and a string, but I would like to know if a variable exists that contains my query name. That way I could have one command I can use in all queries.

View 7 Replies View Related

Automatically Running Sql Query Every Week

Aug 14, 2007

I have a simple query (a select statement which retrieves results from 2 tables via join).  I run this query every week and just copy the results from Management Studio (Ctrl-A) and then open Microsoft Excel and just paste it there.
Is there a way I can automatically run this every week and generate the Excel from the results?  If so what steps I have to do?
I use SQL Server 2005 Express Edition.

View 5 Replies View Related

Send Mail Automatically Using Sql Query

Jun 4, 2008

I have problem using the sp msdb.dbo.sp_send_dbmail....it will give error like "the EXECUTE permission was denied on the object 'sp_send_dbmail', database 'msdb', schema 'dbo'". i am using godaddy...plz help me how to rectify the error...give me the full answer....
 thank
muthu6500

View 3 Replies View Related

Automatically Adding Numbers To Query

Jun 4, 2008

Hello everyone!

I have a question for you. I have a product database with a lookup that pulls by product number. All my product numbers are made up the same way. IE. N59840, N00951, N00951. ect.

I have a stored procedure that looks up by that product number with a "LIKE" statement that looks like this.

WHERE ([Product#] LIKE '%' + @PRODUCTNUM + '%')

Which has this problem if someone types in "852" it returns

N00852
N05852
N98852

Is there anyway that I can have SQL put in zeros to fill up the 5 number spots so "852" brings up "00852" or "5852" brings up "05852"

I hope this makes sense.

Thank you for your help!!!

View 4 Replies View Related

Query Diff Results From Ent Manager Query And Query Analizer

May 28, 2008

ok can someone tell me why i get two different answers for the same query. (looking for last day of month for a given date)

SELECT DATEADD(ms, - 3, DATEADD(mm, DATEDIFF(m, 0, CAST('12/20/2006' AS datetime)) + 1, 0)) AS Expr1
FROM testsupplierSCNCR
I am getting the result of 01/01/2007

but in query analizer I get the result of

12/31/2006

Why the different dates

View 4 Replies View Related

Automatically Trigger A Sum From One Table To Another Upon Update/insert Query

Jul 12, 2005

I'm trying to update (increment)
Company.SumtotalLogons
from CompanyUsers.NumberOfLogons
where CompanyUsers.CompanyID = Company.CompanyID

I'd like to either write a formula (if it is even possible to fire a formula from one table update/insert to increment a field in another table), or a stored procedure that triggers an auto update/append into Company.SumTotalLogons

I know this is possible in access, so i'm wondering how to go about it in ms-sql?

any ideas?

View 1 Replies View Related

Filter Query By Year And Change Dated Automatically

Jan 21, 2014

I have a data column named Date_In with format of 20-May-13. How can I filter the data to select based on year only. I used

Select
*
From apps.xdmc_852@erpprod
Where Year(Date_in) = 2014

This code is not working. I also need a way to automatically update to next week range. For example, last week I used where function like this

Where Date_in = to_date('01/12/2014','MM/DD/YYYY')

Is there a way it will automatically at the next 7 days to the code above when the date is available. This week I have to go back and changed the code in to this:

Where Date_in = to_date('01/19/2014','MM/DD/YYYY')

View 3 Replies View Related

Query Problem: Automatically Resetting A Sequential Number List After Row Deletion

Apr 7, 2004

Hello!
Got a problem I hope some clever people can help me out with..

I have a web form that displays a set of records in a grid. The grid is "paged" according to a PageNum column, with a dropdown box to change pages and buttons allowing the items to be moved up or down a list within a page or moved between pages. So the backend table (simplified) looks something like this

PageNum ItemNum ItemDescription
----------- ----------- -------------------
1 1 aaaaaaa
1 2 bbbbbbb
1 3 cccccccc
2 1 ddddddd
2 2 eeeeeee
2 3 ffffffffffff
3 1 ggggggg
3 2 hhhhhhh
3 3 iiiiiiiiiiiiiiii

The problem is when I want to delete a page - I need the page numbers to automatically resequence themselves, so for example, If I delete "Page 2" (i.e. delete rows where PageNum = 2), all items on "Page 3" become "Page 2" (and any items on "Page 4" become "Page 3" etc).

This has proved straightforward to when deleting an item from a particular page, and can resequence ItemNum thanks to a clever bit of code found on SQLteam.com:

DECLARE @intCounter int
SET @intCounter = 0
UPDATE <Item Table>
@intCounter = ItemNum = @intCounter + 1
WHERE Pagenumber = <Currently Selected Page>

However I haven't been able to adapt this to resequence the Page number, as this involves resequencing blocks of numbers. The closest I can get is:

DECLARE @intCounter int
SET @intCounter = 1
UPDATE <Itemtable>
SET @intCounter = PageNum = CASE
WHEN @intCounter = PageNum - 1 THEN @intCounter + 1
WHEN @intCounter = PageNum - 2 THEN @intCounter + 1
ELSE @intCounter
END

But this doesn't quite work.
Anyone got any other ideas??

Thanks
Greg

View 3 Replies View Related

Query Fails With Invalid Column Name But Succeed As Sub-query With Unexpected Results

Sep 22, 2015

-- The 3rd query uses an incorrect column name in a sub-query and succeeds but rows are incorrectly qualified. This is very DANGEROUS!!!
-- The issue exists is in 2008 R2, 2012 and 2014 and is "By Design"

set nocount on
go
if object_id('tempdb.dbo.#t1') IS NOT NULL drop table #t1
if object_id('tempdb.dbo

[code]....

This succeeds when the invalid column name is a valid column name in the outer query. So in this situation the sub-query would fail when run by itself but succeed with an incorrectly applied filter when run as a sub-query. The danger here is that if a SQL Server user runs DML in a production database with such a sub-query which then the results are likely not the expected results with potentially unintended actions applied against the data. how many SQL Server users have had incorrectly applied DML or incorrect query results and don't even know it....?

View 2 Replies View Related

Transact SQL :: Adding Results Of Query To Another Query Via Dynamically Added Columns

Jul 30, 2015

For each customer, I want to add all of their telephone numbers to a different column. That is, multiple columns (depending on the number of telephone numbers) for each customer/row. How can I achieve that?

I want my output to be

CUSTOMER ID, FIRST NAME, LAST NAME, TEL1, TEL2, TEL3, ... etc

Each 'Tel' will relate to a one or more records in the PHONES table that is linked back to the customer.

I want to do it using SELECT. Is it possible?

View 13 Replies View Related

Easy SQL Question. How To Display Query Results In Query Analyzer

Feb 12, 2008

When I run the following query from Query Analyzer in SQL Serer 2005, I get a message back that says.
Command(s) completed successfully.
What I really need it to do is to display the results of the query. Does anyone know how to do this?
declare     @SniierId as   uniqueidentifierset @SniierId = '85555560-AD5D-430C-9B97-FB0AC3C7DA1F'declare    @SniierAlias  as nvarchar(50)declare    @AlwaysShowEditButton  as bitdeclare     @SniierName  as  nvarchar (128)/* Check access for Sniier */SELECT TOP 1       @SniierName      = Sniiers.SniierName,        @SniierAlias    = Sniiers.SniierAlias,        @AlwaysShowEditButton = Sniiers.AlwaysShowEditButtonFROM SniiersWHERE Sniiers.SniierId=@SniierId

View 3 Replies View Related

Select Query To Get Email Id

Feb 2, 2007

I have three tables as

Employeemaster
Designation
Grade

In grade table i initalised grades for designations from designation table

those designations have been initalised in employeemaster for employees

If I select particular employee code depending on designation iam getting his higher authority designation

now if i select designation from higher authority i need to get particular authority email id from employeemaster




Malathi Rao

View 1 Replies View Related

Query To Get The Domain From The Email

Jul 20, 2005

Hi,I wanted to get the domain name from the email in a query..So if the email is Join Bytes!, I just to display hotmail.comThanks in advance for the help.AJ

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved