Scripting setup of database mail - sql-server-2008

I've used the SQL Server 2008 GUI to set up database mail profiles & accounts on my test server, and I'd now like to duplicate those to our production database.
Is there a way to generate a script to do this?

AFAIK, there isn't a way to necessarily script this from SSMS but you can create a transportable script in TSQL once and reuse it on all the servers. Here is a good example to get you started with this:
USE [master]
GO
sp_configure 'show advanced options',1
GO
RECONFIGURE WITH OVERRIDE
GO
sp_configure 'Database Mail XPs',1
GO
RECONFIGURE
GO
-- Create a New Mail Profile for Notifications
EXECUTE msdb.dbo.sysmail_add_profile_sp
#profile_name = 'DBA_Notifications',
#description = 'Profile for sending Automated DBA Notifications'
GO
-- Set the New Profile as the Default
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
#profile_name = 'DBA_Notifications',
#principal_name = 'public',
#is_default = 1 ;
GO
-- Create an Account for the Notifications
EXECUTE msdb.dbo.sysmail_add_account_sp
#account_name = 'SQLMonitor',
#description = 'Account for Automated DBA Notifications',
#email_address = 'email#domain.com', -- Change This
#display_name = 'SQL Monitor',
#mailserver_name = 'smtp.domain.com' -- Change This
GO
-- Add the Account to the Profile
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
#profile_name = 'DBA_Notifications',
#account_name = 'SQLMonitor',
#sequence_number = 1
GO
The other option would be to leverage SMO, either through .NET or powershell to generate the scripts. The SMO reference for this would be:
SqlMail Class
UPDATE:
Here is how easy it turned out to be to script this with Powershell and SMO:
[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo");
#Set the server to script from
$ServerName = "ServerName";
#Get a server object which corresponds to the default instance
$srv = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Server $ServerName
#Script Database Mail configuration from the server
$srv.Mail.Script();

Related

Error: nanodbc/nanodbc.cpp:1021: 00000: [

I have been trying to connect to my SQL that I am trying to create. I recently downloaded MySQL, the workbench, the connector ODBC, and the ODBC Manager, but I can't find the solution to solve the error for the connection.
Do I need to download anything else? I can't find a solution on internet or youtube for Mac.
packages_required = c("quantmod", "RSQLite", "data.table", "lubridate", "pbapply", "DBI")
install.packages(packages_required)
library("quantmod")
library("RSQLite")
library("data.table")
library("lubridate")
library("pbapply")
library("odbc")
PASS <- new.env()
assign("pwd","My Password",envir=PASS)
library("DBI")
con <- dbConnect(odbc(), Driver = "/usr/local/mysql-connector-odbc-8.0.28-macos11-x86-64bit/lib/libmyodbc8w.so",
Server = "localhost", Database = "data", UID = "root", PWD = PASS$pwd,
Port = 3306)
-----------------------------------------------------------------------------------------
> con <- dbConnect(odbc(), Driver = "/usr/local/mysql-connector-odbc-8.0.28-macos11-x86-64bit/lib/libmyodbc8w.so",
+ Server = "localhost", Database = "data", UID = "root", PWD = PASS$pwd,
+ Port = 3306)
Error: nanodbc/nanodbc.cpp:1021: 00000: [
>
Thank you
Presuming you're on Windows, try creating an ODBC connection using the most recent driver. The ODBC data sources tool should already be installed, you just need to open it and create a new one.
Press the windows key (or click the search spyglass) and type in "ODBC." The "ODBC Data Sources (64-bit)" tool should come up.
How to Create an ODBC Connection in Windows
Open the "ODBC Data Sources (64-bit)" application
Click "Add"
Choose"MySQL ODBC 8.0 Unicode Driver" (or whatever the newest version you
have is). If you don't have it, you can download it here:
https://dev.mysql.com/downloads/connector/odbc/
Enter the following information:
Data source name (the example code below uses "my_odbc_connection"), TCP/IP Server, Port, User and Password
Click "Details" to expand the box.
In the "Connection" tab, you may need to check the "Enable Cleartext
Authentication" box. Could depend on your system configuratoin.
Click "Test" to test the connection. If everything went right you
should get "Connection Successful" message. If you aren't able to get a
successful connection, make sure that you have access and that your
connection information doesn't have any typos.
After making a successful connection, perform these 2 additional steps (the
drop-downs won't populate until you connect successfully):
Click the "Database" drop down to choose the default database that you'll
be writing data to. If you will be writing to more than 1 database
then you may need to create a separate connection for each database
that you'll be writing to, specifying the default database
differently for each one.
Click the "Character Set" drop down and choose utf8.
You should now able to use the "DBI" and "ODBC" packages to read, write, etc. any data directly from R. Specific settings listed above may or may not apply depending on situation.
See the example code below.
Further reading: https://www.r-bloggers.com/setting-up-an-odbc-connection-with-ms-sql-server-on-windows/
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~ Load or install packages
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Load or install librarian
if(require(librarian) == FALSE){
install.packages("librarian")
if(require(librarian)== FALSE){stop("Unable to install and load librarian")}
}
# Load multiple packages using the librarian package
librarian::shelf(tidyverse, readxl, DBI, lubridate, ODBC, quiet = TRUE)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~ Read
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Connect to a pre-defined ODBC connection named "my_odbc_connection"
conn <- DBI::dbConnect(odbc::odbc(), "my_odbc_connection")
# Create a query
query <- "
SELECT *
FROM YOUR_SCHEMA.YOUR_TABLE;
"
# Run the query
df_data <- DBI::dbGetQuery(conn,query)
# Close the open connection
try(DBI::dbDisconnect(conn), silent = TRUE)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~ Write
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Define the connection and database you'll be writing to
conn <- DBI::dbConnect(odbc::odbc(), "my_odbc_connection", db ="YOUR_DEFAULT_DB")
# Define variable types for your data frame. As a general rule, it's a good idea to define your data types rather than let the package guess.
field_types <- c("INTEGER","VARCHAR(20)","DATE","DATETIME","VARCHAR(20)","VARCHAR(50)","VARCHAR(20)")
names(field_types) <- names(df_data)
# Record start time
start_time <- Sys.time()
# Example write statement
DBI::dbWriteTable(conn,"YOUR_TABLE_NAME",YOUR_DATA_FRAME,overwrite=TRUE,field.types=field_types, row.names = FALSE)
# Print time difference
print("Writing complete.")
print(Sys.time() - start_time)
# Close the open connection
try(DBI::dbDisconnect(conn), silent = TRUE)

Sqlcmd - run sql query script without cleartext password?

Hope you're having a great day thus far :)
I'm using this script to automate an sqlquery, so that another team can use these logs. However, they are not permitted to have the login credentials for this database, and my current script uses a cleartext password.
I suggested that we create a new database profile and limit the permissions of the profile, so that only the specific table can be accessed with read-only permissions. However, this isn't best practice, and my lead doesn't like the idea.
So, I'm trying to figure out a way to pass the login credentials through the script, without using cleartext.
Do you have any ideas?
This is the current format of the cmd I'm running in the batch file:
sqlcmd -S server.database.windows.net -U user#domain -P password -d DB_Name -i "c:\users\%USERNAME%\desktop\Blue Prism Audit Logs\eventdatetime24hr.sql" -o "c:\users\%USERNAME%\desktop\Blue Prism Audit Logs\Audit Logs\queryOut%DATE:~4,2%_%DATE:~7,2%_%DATE:~-4%_%time:~0,2%%time:~3,2%.csv"
Expand the SQL Server Agent node and right click the Jobs node in SQL Server Agent and select 'New Job'
In the 'New Job' window enter the name of the job and a description on the 'General' tab.
Select 'Steps' on the left hand side of the window and click 'New' at the bottom.
In the 'Steps' window enter a step name and select the database you want the query to run against.
Paste in the T-SQL command you want to run into the Command window and click 'OK'.
Click on the 'Schedule' menu on the left of the New Job window and enter the schedule information (e.g. daily and a time).
Click 'OK' - and that should be it.
(There are of course other options you can add - but I would say that is the bare minimum you need to get a job set up and scheduled)
example tsql code with output
DECLARE #cmd sysname, #var sysname;
SET #var = 'Hello world';
SET #cmd = 'echo ' + #var + ' > var_out.txt';
EXEC master..xp_cmdshell #cmd;
more info here: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/xp-cmdshell-transact-sql?view=sql-server-ver15
this will create a script that runs whenever you want it to and you set it up on the DB and then you can decide where you put the output i.e. in a target location for the other team to pick it up.

Execute Script task throws error "The package execution returned DTSER_FAILURE (1)"

I have a SSIS package that will load data from a set of excel files then archive those files to a specified folder.
The excel files are stored in a folder and inside that folder I have the archive folder.
Below is my script task code for reference.
public void Main()
{
// TODO: Add your code here
string sourceDir = Dts.Variables["User::strFilePath"].Value.ToString();
string destDir = Dts.Variables["User::strArchivePath"].Value.ToString();
DirectoryInfo di = new DirectoryInfo(sourceDir);
string[] sDirFiles = Directory.GetFiles(sourceDir);
FileInfo[] fi = di.GetFiles("*.xls");
int fileCnt = fi.Length;
for (int i = 0; i < fileCnt; i++)
{
String filename = fi[i].Name;
string[] splitFilename = filename.Split('.');
DateTime dt = DateTime.Now;
string ArchiveDate = String.Format("{0:ddMMMyyyy}", dt);
string sourceFileName = filename;
string sourceFilePath = sourceDir + filename;
string destinationFileName = splitFilename[0] + '_' + ArchiveDate + '.' + splitFilename[1];
string destinationPath = destDir + destinationFileName;
//MessageBox.Show("Source File " + sourceFilePath + " to destination " + destinationPath);
if (File.Exists(destinationPath))
File.Delete(destinationPath);
// To move a file or folder to a new location:
System.IO.File.Move(sourceFilePath, destinationPath);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
The sourceDir and destDir are variables that provides the path of source files folder and archive folder. The package works fine when I run it from visual studio.
I have deployed it to run as a job using deployment utility by creating manifest file. When I run the job I'm getting error in my archive script task. Below is the screenshot of it.
I searched for solution in stackoverflow however the provided solutions does not solve my problem.
Problem using SQL Agent to run SSIS Packages - fails with “DTSER_FAILURE(1)”
DTSX package runs in Visual Studio but not when called from a Database Job
I have granted read write access to SQL server for both the folders. Still getting the same error?
Any help is highly appreciated.
Try choosing 64bit on your Project --> Properties --> Dubugging--> Run64BitTime this could solve the problem.
I replaced the script task with a file system task and it worked. I also created a proxy account to run the package with my system credentials so that it will have the access to the folder specified.
Putting the steps in creating a proxy account for running the SQL job so that it will be helpful for users looking out for it..
Create a User account in SQL under which you need to run the Job
Create a credentials for the user account created.
--Script #1 - Creating a credential to be used by proxy
USE MASTER
GO
--Drop the credential if it is already existing
IF EXISTS (SELECT 1 FROM sys.credentials WHERE name = N'SSISProxyCredentials')
BEGIN
DROP CREDENTIAL [SSISProxyCredentials]
END
GO
CREATE CREDENTIAL [SSISProxyCredentials]
WITH IDENTITY = N'<Insert the Username>',
SECRET = N'abcd#0987'
GO
Create Proxy account and associate the credentials created
--Script #2 - Creating a proxy account
USE msdb
GO
--Drop the proxy if it is already existing
IF EXISTS (SELECT 1 FROM msdb.dbo.sysproxies WHERE name = N'SSISProxyDemo')
BEGIN
EXEC dbo.sp_delete_proxy
#proxy_name = N'SSISProxyDemo'
END
GO
--Create a proxy and use the same credential as created above
EXEC msdb.dbo.sp_add_proxy
#proxy_name = N'SSISProxyDemo',
#credential_name=N'SSISProxyCredentials',
#enabled=1
GO
--To enable or disable you can use this command
EXEC msdb.dbo.sp_update_proxy
#proxy_name = N'SSISProxyDemo',
#enabled = 1 --#enabled = 0
GO
Granting proxy account to SQL Server Agent Sub-systems
USE msdb
GO
--You can view all the sub systems of SQL Server Agent with this command
--You can notice for SSIS Subsystem id is 11
EXEC sp_enum_sqlagent_subsystems
GO
--Grant created proxy to SQL Agent subsystem
--You can grant created proxy to as many as available subsystems
EXEC msdb.dbo.sp_grant_proxy_to_subsystem
#proxy_name=N'SSISProxyDemo',
#subsystem_id=11 --subsystem 11 is for SSIS as you can see in the above image
GO
--View all the proxies granted to all the subsystems
EXEC dbo.sp_enum_proxy_for_subsystem
Granting proxy access to security principals
USE msdb
GO
--Grant proxy account access to security principals that could be
--either login name or fixed server role or msdb role
--Please note, Members of sysadmin server role are allowed to use any proxy
EXEC msdb.dbo.sp_grant_login_to_proxy
#proxy_name=N'SSISProxyDemo'
,#login_name=N'<Insert the Username>'
--,#fixed_server_role=N''
--,#msdb_role=N''
GO
--View logins provided access to proxies
EXEC dbo.sp_enum_login_for_proxy
GO
Finally associate the proxy account to the package step. This can be also done through job wizard.
EXEC msdb.dbo.sp_add_jobstep #job_id=#jobId, #step_name=N'SSISPackageCall',
#step_id=1,
#cmdexec_success_code=0,
#on_success_action=1,
#on_success_step_id=0,
#on_fail_action=2,
#on_fail_step_id=0,
#retry_attempts=0,
#retry_interval=0,
#os_run_priority=0, #subsystem=N'SSIS',
#command=N'/FILE "C:\Package.dtsx" /CHECKPOINTING OFF /REPORTING E',
#database_name=N'master',
#flags=0,
#proxy_name = N'SSISProxyDemo';
Thanks for the valuable replies for my post..

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I am deploying sql express with my application. I will like that database engine to accept remote connections. I know how to configure that manual by launching the sql server configuration manager, enabling tcp/ip connections, specifying the ports etc.. I am wondering if it will be possible to do the same thing from the command line.
Or maybe I will have to create a "SQL Server 2008 Server Project" in visual studio.
EDIT 1
I posted the same question in here but I will like to do the same thing on a instance of sql express that is already installed. Take a look at the question in here
EDIT 2
I found these links that claim on doing something similar and I still cannot make it work.
1) http://support.microsoft.com/kb/839980
2) http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/c7d3c3af-2b1e-4273-afe9-0669dcb7bd02/
3) http://www.sql-questions.com/microsoft/SQL-Server/34211977/can-not-connect-to-sql-2008-express-on-same-lan.aspx
4) http://datazulu.com/blog/post/Enable_sql_server_tcp_via_script.aspx
EDIT 3
As Krzysztof stated in his response I need (plus other things that I know that are required)
1 - enable TCP/IP
I have managed to do this when installing a new instance of SQLExpress passing the parameter /TCPENABLED=1. When I install sql express like in this example. that instance of sql express will have TCP/IP enabled
2 - Open the right ports in the firewall
(I have done this manualy but I belive I will be able to figure it out how to do it with c#)
So far I have to play aroud with this console command:
netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
3 - Modify TCP/IP properties enable a IP address
I have not been able to figure out how to enable a IP, change a port etc.. I think this will be the step more complicated to solve
4 - Enable mixed mode authentication in sql server
I have managed to do this when installing SQL Express passing the parameter /SECURITYMODE=SQL refer to step 1's link.
SQL Server express requires this authentication type to accept remote connections.
5 - Change user (sa) default passowrd
By default the sa account has a NULL passowrd. In order to accept connections this user must have a password. I changed the default passowrd of the sa with the script:
ALTER LOGIN [sa] WITH PASSWORD='*****newPassword****'
6 - finally
will be able to connecto if all the last steps are satisied as:
SQLCMD -U sa -P newPassword -S 192.168.0.120\SQLEXPRESS,1433
by typing that in the command line: the connection string in C# will be very similar. I will have to replace -U for user , -P for password and -S for data source. I dont recall the exact names.
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
1 - Enable TCP/IP
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
2 - Open the right ports in the firewall
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
3 - Modify TCP/IP properties enable a IP address
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
4 - Enable mixed mode authentication in sql server
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.
5 - Change user (sa) default password
You got this one covered.
6 - Finally (connect to the instance)
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server).
However, it was not available in my case.
I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.
# Enable TCP/IP
Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable
# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433
# Modify TCP/IP properties to enable an IP address
$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments #{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments #{ StrValue = '' }
# Restart SQL Server
Restart-Service 'MSSQL$SQLEXPRESS'

connection of MATLAB 7.0 and MYSQL

I want to connect MATLAB with MYSQL.I dont know the procedure.In MATLAB help it says about some drivers which confuses me alot.Can someone please guide me!please tell me the complete process.I shall be very very thankful!!!
I use JDBC to connect from MATLAB to mySQL database. Works seamlessly.
First download JDBC driver for mySQL from here:
http://www.mysql.com/downloads/connector/j/
Unpack mysql-connector-java-x.x.xx-bin.jar (the latest version) file from the archive into a folder
In the beginning of your script add the path to this jar file, then you can connect to a database and so on.
Here is an example of connecting to and querying public human genome database:
%# add path to the JAR file you just installed to Java dynamic classpath
javaaddpath('h:\Documents\MATLAB\myJavaClasses\mysql-connector-java-5.1.12-bin.jar')
%# connection parameteres
host = 'genome-mysql.cse.ucsc.edu';
user = 'genome';
password = '';
dbName = 'hg18';
%# JDBC parameters
jdbcString = sprintf('jdbc:mysql://%s/%s', host, dbName);
jdbcDriver = 'com.mysql.jdbc.Driver';
%# Create the database connection object
conn = database(dbName, user , password, jdbcDriver, jdbcString);
gene = 'NF1';
if isconnection(conn) % check to make sure that we successfully connected
qry = sprintf('SELECT geneName, chrom, txStart, txEnd FROM refFlat WHERE geneName=''%s''',gene);
rs = fetch(exec(conn, qry));
rsdata = get(rs, 'Data');
end