Execute SQL Task Email - sql-server

I am getting issue sending email from "Execute SQL Task"
failed with the following error:
"Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Here is SQL Statement-
USE msdb
GO
EXEC
sp_send_dbmail
#profile_name='DBAAdminSF',
#recipients='Aslone#yahoo.com',
#subject='Data uploaded',
#body=?
Parameter Mapping:
Variable Name User::Email_DB
Parameter Name =#body
It works fine when I include text for #body parameter directly in the query instead of using Parameter Mapping.
Help appreciated.

Have you tried overriding the script with Expressions instead of parameter mapping?
Sample Expression override i used for a recent project:
"Exec msdb.dbo.sp_send_dbmail
#profile_name='Email Profile',
#recipients='email_addy',
#copy_recipients='email_addy',
#subject=N'Subject Text" + #[User::FileMonth] + "',
#body=N'Body Text" + #[User::FileMonth] + "' ,
#file_attachments=N'" + #[User::FilePath] + "' "

Related

Updating a SQL record with Powershell

It's me again, I'm still getting to limited grips about how PowerShell and SQL work together, this isn't my main field of experience so please excuse the simple mistake I've probably made.
I am trying to update one field in a row. I've searched here and been able to build most of what I need but am getting an error message that states
"Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near 'f7'."
At line:61 char:5
+ $rowsAffected = $command2.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException"
This is the code snippet I am using is this section, it is embedded within a foreach loop that steps through the rows of a dataset and sends an email. This section is supposed to change the bit type field "mailed" to true which ensure that only one email is sent per record.
$connect2 = New-Object System.Data.SqlClient.SqlConnection
$connect2.ConnectionString=$ServerConnection
$connect2.Open()
$command2 = New-Object System.Data.SqlClient.SqlCommand
$command2.Connection = $connect2
$MySql2="UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ="+$BT1
$command2.CommandText = $MySql2
$rowsAffected = $command2.ExecuteNonQuery()
Write-Output "Updating mailed marker"
$connect2.Close()
EBGreen's suggestion worked perfectly. Changing the text string for the $MySql2 = "UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ='"+$BT1+"'" fixed the error and the field is being updated as required.
Try displaying your sql string to make sure it looks correct. It could be that your $BT1 variable is blank.
write-host $MySql2
Also, when dealing with sql syntax errors it is helpful to log in directly to the sql server and submit the string through the sql command line shell. Once you can submit the string successfully from the command line then check that your powershell string looks exactly the same.
You can make your query string setup more basic. Within PowerShell if you reference a variable with double-quotes, PowerShell will resolve that variable to the set value.
So instead of doing this:
$MySql2="UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ="+$BT1
Or even this:
$MySql2="UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ='"+$BT1+"'"
You can simply do this:
$MySql2="UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ='$BT1'"

How to create a Database user in Entity Framework

Been working on my first Entity Framework project. As part of the project I am going to be creating a number of SSRS reports. In order to connect to the database I need to have a Reports user that will only access to the specific database on the server. In the past i have always written a script to add Database users but I want to know is there a way that i can do this using Entity Framework instead?
Assuming your user already has a login defined at the SQL Server level (Security > Logins), you can call the following method from your DB initializer seed method to add the user to the database:
private void AddDbUser(MyDataContext myDB)
{
string accountDomainName = "AccountDomainName"; // replace with user's login domain
string accountLoginID = "AccountLoginID"; // replace with user's login ID
string sql =
"USE [MyDB]" +
"CREATE USER [MyNewUser] FOR LOGIN [" + accountDomainName + "\\" + accountLoginID + "]" +
"ALTER AUTHORIZATION ON SCHEMA::[db_datareader] TO [" + accountLoginID + "]" +
"ALTER AUTHORIZATION ON SCHEMA::[db_datawriter] TO [" + accountLoginID + "]" +
"EXEC sp_addrolemember N'db_datawriter', N'" + accountLoginID + "'" +
"EXEC sp_addrolemember N'db_datareader', N'" + accountLoginID + "'";
myDB.Database.ExecuteSqlCommand(sql);
}
The exact SQL needed is dependent on your configuration. To have SQL Server generate the SQL for your scenario, you could open the add user dialog in SSMS (Database > Users > New User...), fill out the fields, and click the "Script" button at the top instead of hitting OK at the bottom. Note that any "GO" lines will need to be removed from the generated script before pasting it into the method above.
You would need to tell EF to use the appropriate stored procedures to do so. You could also wrap these up in a sproc of your own that wraps the relevant commands. There is no native "CreateReportsUser" type method within EF that I know of.
Edit: I probably should have provided this reference to be a "complete" answer. Apologies.
Here's how you can do what I recommend: How to call Stored Procedure in Entity Framework 6 (Code-First)?

Calling an SQL Sever stored procedure with a date parameter in an ADODB.Connection.execute() command method in VB

I am trying to run an ADO execute method with a SQL stored procedure that uses a date parameter to run. I made sure the data type of the parameter matched what it is defined as in the stored procedure (INT). The variable the stored procedure seems to have it formatted correctly as well (sp_StoredProcedureName 20151019). The connection to the SQL server just times out at the specified time of 720 seconds. Earlier in my program, I have another ADO execute method that doesn't seem to have any issues running. However, there is no parameter needed to run that procedure.The stored procedure seems to execute fine when I execute it in SQL server management studio. Is there a reason my other stored procedure isn't running?
This is the section that runs fine
strSQL = "sp_BuildInvoiceDate"
cnn2SQL.Execute(strSQL, lngRecordsAffected, ADODB.ExecuteOptionEnum.adExecuteNoRecords)
WriteLog((lngRecordsAffected & " updates using '" & strSQL & "'"))
Here is the code that times out
strSQL = "sp_UpdateCreditHeader " & varTemp
'ERROR: -2147217871 - Query timeout expired
cnn2SQL.Execute(strSQL, lngRecordsAffected, ADODB.ExecuteOptionEnum.adExecuteNoRecords)
WriteLog((lngRecordsAffected & " updates using '" & strSQL & "'"))
varTemp is defined in a previous step as an integer just as it is defined on the server.
It was actually just a matter of the order of the code. I placed the Stored Procedure at the bottom of my code and it worked...

Passing Large XML data to xml datatype parameter in ADODB

I have a procedure that takes a xml datatype parameter
create procedure my_procedure
#xml_parameter xml
as
begin
(...)
end
And i call that procedure from a classic asp page, using a command like this:
set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = MyConnObj
cmd.CommandText = "my_procedure"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Append cmd.CreateParameter("#xml_parameter", adLongVarChar, adParamInput, Len(xmlData), xmlData)
It's working if i pass a small xml. But when i pass a large xml, +- 200 Kb, I get the message "The procedure expects the #xml_parameter parameter, wich was not informed".
Does anyone know how i can pass this xml to the stored procedure?
PS: It also works when i call the procedure from "SQL Server Management Studio" with the same xml data, so it seems the limitation is from the ADO.
Edit in 2014-jun-19:
Debugging the problem i discovered a message from ODBC Driver saying that some data are being truncated. I tried to change the driver, by using "Driver={SQL Server Native Client 11.0}", but now i get the message : "The metadata could not be determined because statement (...) uses a temp table"
I was able to successfully submit over 7MB of data into procedure's parameter by using ADODB 2.8, Parameters.Refresh method to initially build the parameters, AppendChunk method to built its value and changing parameter's type to adLongVarWChar before execution (originally it was adVarWChar)
.Refresh query the database for parameters, hence you get an extra DB communication.
all need to be done instead of refresh is pass the length as Len+1, for the null terminating character.

Convert string to uniqueidentifier in VBScript

I have a script that runs a stored procedure in my SQL server database, the problem is the stored procedure takes a uniqueidentifier parameter. I have a function that grabs a session id from the database (which is an nvarchar), so VBScript makes it a string and I need to convert it to pass it to the stored procedure.
Function GetOpenSession
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
conn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=" & Source
rs.CursorLocation = 3
rs.Open "SELECT top 1 OpenSession FROM OpenSessions with (nolock)" , conn, 3, 3
If rs.RecordCount = 0 Then
MsgBox "No Connection"
Else
GetOpenSession = rs.Fields(0).Value
End If
End Function
I get "Invalid character value for cast specification" when I try to execute the stored procedure.
set cnParam = cmd.CreateParameter("#ActiveSession",72,1,,GetOpenSession)
cmd.Parameters.Append cnParam
I can't change anything in the database, so I need a way to overcome this in my script.
I believe VBScript expects GUIDs to be brace terminated.
Is your Session id of the same format as the following {D6CA6263-E8E1-41C1-AEA6-040EA89BF030}
Depending on the data type of the SELECT OpenSession, you may be able to cast/convert it in the query and VBScript may possibly keep the data type as a GUID:
SELECT top 1 CONVERT(uniqueidentifier, OpenSession)
FROM OpenSessions with (nolock)
When you use GetOpenSession or rs.Fields(0).Value, hopefully VBScript will keep it as a GUID.
The other possibility seems to be a Win32 API using CoCreateGuid and StringFromGUID2. An example is found here, but it requires external Win32 functions and a Type for GUID.
I usually change the parameter type of the stored procedure to varchar(38).
SQL Server makes a better job of coercing the string to a GUID when needed.
What is the value of GetOpenSession after you have assigned it? Which datatype? It sounds like it is not compatible with type 72 (GUID), which you are stating in the CreateParameter call.
You could forget about using ADO Commands altogether and just execute the stored procedure using plain SQL.
Set rs = CreateObject("ADODB.Recordset")
rs.Open "EXEC usp_MySP '" & GetOpenSession & "'", cnn
Obviously it's terrible to build SQL commands like this, but it's just for a test, after all...

Resources