473,394 Members | 1,828 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

SQL newbie needs help automating query to send via email

Hello all,

I'm new to using SQL and I'm trying to create a "script" if that is the proper term for it; to automatically pull a query that I have created successfully in a manual process and then have it automatically sent via email to a user so they can act upon the data. any ideas are appreciated.

I'm using SQL Distr Mgmt Framework (SQL-DMF) ver SQL 8.00.2039.

Thanks!
Aug 6 '07 #1
3 1861
Hello all,

I'm new to using SQL and I'm trying to create a "script" if that is the proper term for it; to automatically pull a query that I have created successfully in a manual process and then have it automatically sent via email to a user so they can act upon the data. any ideas are appreciated.

I'm using SQL Distr Mgmt Framework (SQL-DMF) ver SQL 8.00.2039.

Thanks!
The way I have done this in the past is to use SQL Mail. Its a little cumbersome to set up as you must install a MAPI client on your SQL server. I was able to use Outlook for this, but you can use others as well. You also need an exchange server, or compatible pop3 mail server.

Here's an article that should get you started.
http://support.microsoft.com/kb/263556

Another alternative you might look into is called XPSMTP. It doesn't require the use of any special software on your SQL server, but it still requires a mail server. Here is the site for that.
XPSMTP
Aug 10 '07 #2
teddarr
143 100+
If you have the Business Intelligence Development Studio (comes with SQL Server developer edition and Visual Studio 2005 academic versions to name a few) you should look into using an SSIS package. Before SQL Server 2005 they were called DTS packages. This will allow you to automate this process and then go to the sever agant and schedule the task to happen on the schedule you require.
Aug 13 '07 #3
I wrote a ruby script to provide this kind of functionality and it's pretty damn easy to use. All configuration is done in the script itself and all you need to do is have ruby/dbi installed and schedule the script. Here's a sample to get you going. Be sure to replace the references to $global accordingly.
Expand|Select|Wrap|Line Numbers
  1. require "date"
  2. require "dbi"
  3. require "logger"
  4. require "../../globals"
  5.  
  6. module ERM
  7.     class Backlog        
  8.         def initialize(accounts)
  9.             @log = Logger.new("backlog.log")
  10.             @log.level = Logger::INFO
  11.             @log.info("Initializing")
  12.  
  13.             @accounts = accounts
  14.             @queries = Hash.new
  15.             @queries["Archive"] = Hash.new
  16.             @queries["Archive"]["header"] = "Archiving Progress Report"
  17.             @queries["Archive"]["mapping"] = {}
  18.             @queries["Archive"]["query"] = <<EOQ
  19.                 select max(import_date) Imported,max(message_date) Date,max(import_date)-180 Target,datediff(day,max(message_date),max(import_date)-180) Diff
  20.                 from rmarchivedb.dbo.message
  21.                 where import_date >= '2007/08/04'
  22.                 group by convert(varchar,import_date,111)
  23.                 order by Imported desc
  24. EOQ
  25.  
  26.             @queries["OldestPerBox"] = Hash.new
  27.             @queries["OldestPerBox"]["header"] = "Oldest Message Per Box"
  28.             @queries["OldestPerBox"]["mapping"] = {"mailboxids" => "{1}"}
  29.             @queries["OldestPerBox"]["query"] = <<EOQ
  30.                 select convert(varchar,name) Mailbox,min(time) OldestMessage from
  31.                 (
  32.                     select
  33.                     rgm.name,rm.message_id,max(rml.time) time
  34.                     from rm_message rm
  35.                     join rm_group_mailbox rgm on rm.group_mailbox_id = rgm.group_mailbox_id 
  36.                     join rm_log rml on rm.message_id = rml.message_id
  37.                     where 
  38.                     rm.message_status_id = 4 and 
  39.                     rm.group_mailbox_id in ({1}) and 
  40.                     rm.thread_id is not null and 
  41.                     rm.assigned_user_id is null and 
  42.                     rm.is_auto_assignable = 1
  43.                     group by rgm.name,rm.message_id
  44.                 ) a
  45.                 group by name
  46. EOQ
  47.  
  48.             @queries["Unassigned"] = Hash.new
  49.             @queries["Unassigned"]["header"] = "Unassigned Messages"
  50.             @queries["Unassigned"]["mapping"] = {"mailboxids" => "{1}"}
  51.             @queries["Unassigned"]["query"] = <<EOQ
  52.                 select Mailbox,Count from
  53.                 (
  54.                 select case when rgm.[name] is null then 1 else 0 end as Sort,
  55.                 convert(varchar,isnull(rgm.[name],'Total')) [Mailbox],count(*) [Count]
  56.                 from rm_message rm,rm_group_mailbox rgm 
  57.                 where 
  58.                     rm.message_status_id = 4 and 
  59.                     rm.group_mailbox_id in ({1}) and 
  60.                     rm.thread_id is not null and 
  61.                     rm.assigned_user_id is null and 
  62.                     rm.is_auto_assignable = 1 and
  63.                     rm.group_mailbox_id = rgm.group_mailbox_id 
  64.                 group by rgm.[name] with rollup
  65.                 ) a
  66.                 order by sort, Mailbox                                                       
  67. EOQ
  68.             @queries["PerBoxPerDay"] = Hash.new
  69.             @queries["PerBoxPerDay"]["header"] = "Backlog Summary Per Box Per Day"
  70.             @queries["PerBoxPerDay"]["mapping"] = {"mailboxids" => "{1}"}
  71.             @queries["PerBoxPerDay"]["query"] = <<EOQ
  72.                 select convert(varchar,isnull(Mailbox,'')) Mailbox,isnull(Date,'Total') Date,[Count] from
  73.                 (
  74.                     select case when rgm.[friendly_name] is null then 1 else 0 end as Sort,
  75.                     rgm.friendly_name as Mailbox,Convert(varchar,[time],111) as [Date],count(*) as [Count]
  76.                     from rm_log rml,rm_group_mailbox rgm 
  77.                     where log_id in 
  78.                     (
  79.                         select max(log_id) as log_id from rm_log where message_id in 
  80.                         (
  81.                             select message_id
  82.                             from rm_message
  83.                             where message_status_id = 4 and assigned_user_id is null and group_mailbox_id in ({1}) and is_auto_assignable = 1
  84.                         )
  85.                         and activity_type_id = 1 and message_type_id = 1
  86.                         group by message_id
  87.                     )
  88.                     and rml.group_mailbox_id = rgm.group_mailbox_id
  89.                     group by rgm.friendly_name ,Convert(varchar,[time],111) with rollup
  90.                 ) a
  91.                 where not (Mailbox is not null and [Date] is null)
  92.                 order by Sort,[Date]
  93. EOQ
  94.             @queries["OldMessages"] = Hash.new
  95.             @queries["OldMessages"]["header"] = "Backlog Detail of Older Messages"
  96.             @queries["OldMessages"]["mapping"] = {"mailboxids" => "{1}","cutoff" => "{2}"}
  97.             @queries["OldMessages"]["query"] = <<EOQ
  98.                 select convert(varchar,rgm.friendly_name),convert(varchar,[Time],120) as [Time],thread_id
  99.                 from rm_log rml,rm_group_mailbox rgm 
  100.                 where log_id in 
  101.                 (
  102.                     select max(log_id) as log_id from rm_log where message_id in 
  103.                     (
  104.                         select message_id
  105.                         from rm_message
  106.                         where message_status_id = 4 and assigned_user_id is null and group_mailbox_id in ({1})  and is_auto_assignable = 1
  107.                     )
  108.                     and activity_type_id = 1 and message_type_id = 1
  109.                     group by message_id
  110.                 )
  111.                 and rml.group_mailbox_id = rgm.group_mailbox_id
  112.                 and [Time] < getdate() - {2}
  113.                 order by [Time]
  114. EOQ
  115.             @queries["TurnAround"] = Hash.new
  116.             @queries["TurnAround"]["header"] = "Turn Around Time Detail"
  117.             @queries["TurnAround"]["mapping"] = {"date" => "{1}"}
  118.             @queries["TurnAround"]["query"] = <<EOQ
  119.                 select convert(varchar,ms_user.name) Username,replied.thread_id ThreadID,assigned.time Assigned,replied.time Replied
  120.                 from rm_log replied
  121.                 join ms_user on replied.user_id = ms_user.user_id
  122.                 join 
  123.                 (
  124.                     select rm_log.message_id,rm_log.time 
  125.                     from rm_log 
  126.                     join
  127.                     (
  128.                         select 
  129.                         max(log_id) log_id
  130.                         from rm_log
  131.                         where    
  132.                         activity_type_id = 3
  133.                         and message_type_id = 1
  134.                         and new_user_id is not null
  135.                         and message_id = message_id
  136.                         and time >= getdate()-7
  137.                         group by message_id
  138.                     ) t on rm_log.log_id = t.log_id
  139.                 ) assigned on replied.original_message_id = assigned.message_id
  140.                 where 
  141.                 convert(varchar,replied.time,111) = convert(varchar,'{1}',111)
  142.                 and replied.activity_type_id = 4
  143.                 and replied.message_type_id = 2
  144.                 order by name,assigned.time
  145. EOQ
  146.  
  147.         end
  148.  
  149.         def mkSql(report,params)
  150.             @log.debug("mkSql(#{report},#{params.inspect})")
  151.             sql = String.new(@queries[report]["query"]) #If you don't create a copy, it modifies the class variable
  152.             @queries[report]["mapping"].each_pair do |src,dest|
  153.                 sql.gsub!(dest,params[src].to_s) #Apply the mapping
  154.             end
  155.             @log.debug("#{sql}")
  156.             return sql
  157.         end
  158.  
  159.         def run            
  160.             begin
  161.                 runTime = ARGV[0].nil? ? Time.now : Time.parse(ARGV[0])
  162.                 @accounts.each_pair do |account,params|
  163.                     if not params["enabled"].nil? and params["enabled"] then                    
  164.                         params["times"].split(",").each do |time|
  165.                             delta = runTime - Time.parse(time)
  166.                             if delta >= 0 and delta <= 120 then #2 minute tolerance for job to run
  167.                                 begin
  168.                                     DBI::connect(params["connstr"]) do |dbh| #Connect to database
  169.                                         output = ""
  170.                                         params["reports"].split(",").each do |report| #Cycle thru each report
  171.                                             @log.info("Processing #{account} - #{report}")
  172.                                             output << "#{@queries[report]['header']}\n"
  173.                                             sth = dbh.execute(mkSql(report,params))
  174.                                             rows = sth.fetch_all
  175.                                             if rows.length > 0 then
  176.                                                 col_names = sth.column_names                                        
  177.                                                 DBI::Utils::TableFormatter.ascii(col_names,rows,:left,:right,0,0,nil,output)
  178.                                                 output << "\n"                                        
  179.                                             else                                        
  180.                                                 output << "Nothing to report today\n\n"
  181.                                             end
  182.                                             sth.finish                                    
  183.                                         end
  184.                                         @log.info("Emailing report for #{account}")
  185.                                         sendmail("Backlog@#{account}",$globals[:alwaysnotify].split(",") + params["notify"].split(","),"Daily Backlog Report",output)                                    
  186.                                     end
  187.                                 rescue => e
  188.                                     @log.error(e)
  189.                                     sendmail("Error@Backlog",$globals[:alwaysnotify].split(","),"Error running report",e)
  190.                                 end
  191.                             end
  192.                         end                
  193.                     end
  194.                 end
  195.             rescue => e
  196.                 @log.error(e)
  197.                 sendmail("Error@Backlog",$globals[:alwaysnotify].split(","),"Error running report",e)
  198.             ensure
  199.                 @log.info("Done")
  200.             end
  201.         end
  202.  
  203.         def to_s
  204.             s = ""
  205.             @queries.each_pair do |key,value|
  206.                 s << sprintf("%s:\n%s\n",key,value)
  207.             end        
  208.             return s            
  209.         end
  210.     end
  211. end
  212.  
  213. if __FILE__ == $0 then
  214.     accounts = Hash.new
  215.     accounts["Sample"] = Hash.new
  216.     accounts["Sample"]["enabled"] = true
  217.     accounts["Sample"]["connstr"] = "DBI:ADO:Provider=SQLOLEDB;Data Source=DBServer1;Initial Catalog=dbSample;User ID=Sample;Password=Sample123"
  218.     accounts["Sample"]["hours"] = 24
  219.     accounts["Sample"]["cutoff"] = accounts["Sample"]["hours"].to_f/24
  220.     accounts["Sample"]["notify"] = "user1@domain.com,user2@domain.com"
  221.     accounts["Sample"]["mailboxids"] = "12,14,34,36,38,40,42,44,46"
  222.     accounts["Sample"]["reports"] = "PerBoxPerDay,OldMessages"
  223.     accounts["Sample"]["times"] = "0:00"
  224.  
  225.     backlog = ERM::Backlog.new(accounts)
  226.     backlog.run
  227. end
  228.  
Oct 4 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Limey Drink | last post by:
Hi all, Firstly :-) , is there any where I can search through archived newsgroup posts so I am not cluttering up the newsgroup with repeated queries ? And secondly :-), I know this has...
5
by: jason | last post by:
I could sure use some conceptualization and query help with a Page Watch System I am building in Access 2000 and Asp. I need to cycle through databae and generate a compiliation query email that...
8
by: Liam.M | last post by:
Hey guys.... I need to find a way to loop through all of my records in the database ( so essentially query the database) based on a Date Field ("DueDate") and if any record falls within 2 months...
1
by: Liam.M | last post by:
HEY GUYS, need some urgent help here....I am querying my database based on a DueDate field...and want to send an automated email to anyone that falls within two months PRIOR to this "DueDate",...
8
by: Jimbo | last post by:
Hello I am currently designing an internal ordering system for IT equipment. I am designing it in ASP.NET (vb) using Visual Studio 2003 and using Microsoft SQL Server I have got the system...
3
by: sportygeek3 | last post by:
Hi All, I am looking for a way to automate other applications programatically. Is there any C# library that will allow me to do this? i.e. I want to be able to iterate the menu items on...
13
by: Baldaris | last post by:
Show.php--This is for showing movie names available in database <?php include "auth.php"; $query="SELECT movie_id,movie_name FROM moviesite"; $result=mysql_query($query,$link) or die("Can't...
0
by: brossyg | last post by:
I have some VBA code that creates an email in Access and sends it from Outlook. It is based on a query with a list of email addresses. It sends the first email to Outlook and then I have to manually...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.