未加星标

How To Schedule SQL Scripts On SQL Server Express Edition

字体大小 | |
[数据库(mssql) 所属分类 数据库(mssql) | 发布者 店小二03 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

By:Joe Gavin | Last Updated: 2019-01-02 || Related Tips:More > Express Edition

Problem

You need to automate running some SQL, but the is you need to run it directly on an Express Edition of SQL Server that doesn't have the SQL Server Agent we know and love.How can you automate tasks for SQL Server Express?

Solution

PowerShell provides an easy way to script SQL tasks and the native windows Task Scheduler, while not as capable as theSQL Server Agent will work quite nicely for us.

Example Query - Find Latest Backup for All Databases

For example, say we want to get an automated report of the last database backup for each database on a server automatically emailed in a format that can be opened with Excel. We'll start with a SQL query to gather the data, demonstrate three different ways to run the query with the Invoke-SqlCmd PowerShell cmdlet, redirect the output to a .csv file, email the .csv and finally run all of it against more than one SQL Servers.

This query from this blog will show us what we need. I've just added one field to show the server name which will come in handy later.

SELECT @@SERVERNAME AS ServerName, sdb.Name AS DatabaseName, COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTime
FROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
GROUP BY sdb.Name

Running it from SQL Server Management Studio (SSMS) shows a nice clean output like this:


How To Schedule SQL Scripts On SQL Server Express Edition

The next step is to call it with the PowerShell cmdlet Invoke-SqlCmd.

First example, we'll call the SQL query from the input file C:\scripts\GetLatestBackupDates.sql with the Invoke-SqlCmd -InputFile switch.

# pass sql script
$sqlserver = "JGAVIN-L\SQL2016"
Invoke-Sqlcmd -ServerInstance $sqlserver -Database msdb -InputFile "C:\scripts\GetLatestBackupDates.sql"

Second example, we'll call the SQL directly on the command line Invoke-SqlCmd -Query switch.

# call sql direct on command line
$sqlserver = "JGAVIN-L\SQL2016"
Invoke-Sqlcmd -ServerInstance $sqlserver -Database msdb -Query "SELECT sdb.Name AS DatabaseName, COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTime FROM sys.sysdatabases sdb LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name GROUP BY sdb.Name"

Third example, still using -Query but the SQL is declared in a PowerShell variable that is passed to it.

# declare sql in a variable and pass it to -Query switch
$sqlserver = "JGAVIN-L\SQL2016"
$sql="
SELECT sdb.Name AS DatabaseName,
COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTime
FROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
GROUP BY sdb.Name
"
Invoke-Sqlcmd -ServerInstance $sqlserver-Database msdb -Query $sql

Running each of these shows all three methods give us the same output.


How To Schedule SQL Scripts On SQL Server Express Edition
Email SQL Server Backup Query Results as an Attachment

Next, before we can email an attached file we must create it. The output is piped to a .csv with the Export-Csv, then attach it to an email and send it with Send-MailMessage. We'll stay with our third example to keep it more readable.

Add variables to define a file name, mail server, email from and email to Pipe the output to a .csv thru the Export-Csv cmdlet Use the cmdlet Send-MailMessage to email it as an attachment # declare sql in a variable and pass it to -Query switch
$sqlserver = "JGAVIN-L\SQL2016"
$outfile = "$env:TEMP\LastBackupTimes.csv" # name of file to email
$PSEmailServer = "smtp.domain.ext" # mail server name
$emailfrom = "[email protected]" # doesn't have to be real email, just in the form [email protected]
$emailto = "[email protected]"
$sql="
SELECT sdb.Name AS DatabaseName,
COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTime
FROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
GROUP BY sdb.Name
"
# delete old out file if it exists
If (Test-Path "$outfile"){Remove-Item "$outfile"}
# run sql and export to .csv
Invoke-Sqlcmd -ServerInstance $sqlserver -Database msdb -Query $sql | Export-Csv $outfile -NoTypeInformation
# email report file
Send-MailMessage -To $emailto -From "$emailfrom" -Subject "Latest Backup Dates" -Attachments $outfile

Before we schedule it let's make it a little more useful by adding the capability to run this on more than one SQL Server. We just need to do a couple of more things.

Change the $sqlserver variable to an array called $sqlservers and enter the SQL Server names to it quoted and comma separated Add a -Append to the Export-Csv so we don't overwrite the file Save the script as GetLatestBackupDates.ps1 # declare sql in a variable, pass it to -Query switch, export to .csv and send as mail attachment
Param ([array] $sqlservers = @("JGAVIN-L\SQL2016","JGAVIN-L\SQL2017"))
$outfile = "$env:TEMP\LastBackupTimes.csv" # name of file to email
$PSEmailServer = "smtp.domain.ext" # mail server name
$emailfrom = "[email protected]" # doesn't have to be real email, just in the form [email protected]
$emailto = "[email protected]"
$sql="
SELECT @@SERVERNAME AS ServerName, sdb.Name AS DatabaseName, COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_da

本文数据库(mssql)相关术语:熊片数据库 mssql数据库 oracle数据库 pubmed数据库 access数据库 万方数据库

代码区博客精选文章
分页:12
转载请注明
本文标题:How To Schedule SQL Scripts On SQL Server Express Edition
本站链接:https://www.codesec.net/view/628346.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 数据库(mssql) | 评论(0) | 阅读(56)