Variables not recognized in an Execute SQL task - ssis

I have this sql statements running in my ssis package. I have hard coded the email address. How can i pass it as variable and externalize the variable and can pass the value from config file?
The #PackageStartTime is the system start time. I have declared that variable and set the expression in property window with #[System::StartTime] and evaluated that expression. But when i run this package and when it hits this particular task it get stuck at there saying PackageStartTime parameter is not recognized and result property is not set correctly.
Here is my code:
DECLARE #PackageStartTime Varchar(250)
SET #PackageStartTime =?
IF (SELECT COUNT(*) FROM [dbo].[Table1] WHERE RowCDate >= #PackageStartTime) > 0
BEGIN
DECLARE #SUB Varchar(250)
SET #SUB = 'File Failed' + ##SERVERNAME
DECLARE #BODY Varchar(250)
SET #BODY = 'File Failed' + ##SERVERNAME
EXEC msdb.dbo.sp_send_dbmail
#profile_name='default',
#recipients='dev#null.com',
#subject=#SUB,
#body=#BODY,
#query= 'SELECT DISTINCT FileLoadName FROM [dbo].[Table1] WHERE RowCDate >= #PackageStartTime',
#attach_query_result_as_file=1
Any idea what to solve these two things?
Thanks in advance.

Maina, I just responded to your another post on this subject. You have three posts so far that I have encountered. The questions you have asked in this one are very general in nature and the answer can be found in any good book (such as Professional Microsoft SQL Server 2008 Integration Services). You can also find complete step-by-step answer on many websites (but do not use them as a replacement of a book; otherwise chances are your knowledge of SSIS will remain patchy.
With that said, here are two links that answer your questions:
1. Passing a variable: https://www.simple-talk.com/sql/ssis/passing-variables-to-and-from-an-ssis-task/ (Actually, it appears I had sent this link to you earlier as well.)
Assigning variable values from config - http://www.bidn.com/blogs/DevinKnight/ssis/1655/passing-values-into-an-ssis-package-at-runtime-from-outside-the-package
Focus on item 1 first. After you have practiced it, create a new Execute sql task and put just his much code inside it:
DECLARE #PackageStartTime Varchar(40)=?;
SELECT COUNT(*) FROM [dbo].[Table1] WHERE RowCDate >= #PackageStartTime;
and store this row count in a package variable iCount. Returning the value is done through ResultSet property. If you are able to make this task work, you have enhanced your proficiency in Execute SQL Task.

Related

MS SQL Linked Servers And Using In FROM Clause

I have a very basic test stored procedure, shown below. This proc is reading data in a different database, in a different server. To do this I am using a linked server. From what I have read, I need to change the FROM clause to this:
[linked server name].[database name].[schema name].[table name]
However, I would like to pass in the linked server name and database name as parameters and use them in my FROM clause. I am not concerned with injection attacks, etc. I will be passing this in from a config file.
create PROC [dbo].[SelectTEST]
#GU UNIQUEIDENTIFIER,
#LINKED_SERVER_NAME nvarchar(max),
#DATABASE_NAME nvarchar(max)
AS
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRAN
SELECT [GU]
FROM '[' + #LINKED_SERVER_NAME +'].['+ #DATABASE_NAME + '].[Test Table] '
WHERE ([GU] = #GU OR #GU IS NULL)
COMMIT
This is a big mess of syntax errors. Is it possible to pass in these parameters and use in my stored procedure? I would have to make this change to a bunch of different procs, so sorta trying to find the a succinct solution...

Send db mail task fails in SSIS Package with errors related to the parameter

I am trying to execute this sql task in SSIS package which send an email when the file name is not found. I have declared this user-defined variable "#PackageStartTime" in my ssis package. But when my SSIS package hit this task it fails with following error.
"Executing query DECLARE #PackageStartTime Varchar(250) SET #Packag...." failed with the error.: "Parameter name is unrecognized."
Possible failure reasons: Problem with the query, "ResultSet" Property not set correctly, parameters not set correctly, or connection not established correctly."
DECLARE #PackageStartTime Varchar(250)
SET #PackageStartTime =?
IF(SELECT COUNT(*)
FROM [dbo].[Table1] WHERE RowCDate >=#PackageStartTime)>0
BEGIN
DECLARE #SUB Varchar(250)
SET #SUB = 'File Failed'+##SERVERNAME
DECLARE #BODY Varchar(250)
SET #BODY = 'File Failed'+##SERVERNAME
EXEC msdb.dbo.sp_send_dbmail #profile_name='default',
#recipients='dev#null.com',
#subject=#SUB,
#body=#BODY,
#query= 'SELECT DISTINCT FileLoadName
FROM [dbo].[Table1] WHERE RowCDate >=#PackageStartTime',
#attach_query_result_as_file=1
I am unable to understand. I have just added a variable User::strPackageStartTime as Datatype = String and Value is blank. I don't have that variable in parameter mapping in Execute SQL Task Editor. Is there I am missing something?
Thank in advance
I am fairly sure that you cannot pass a parameter into a script like that from SSIS, but you can pass it into a stored procedure. So wrap all of that up in a stored procedure with a parameter. The following code creates your stored procedure.
Then you call it with
EXEC p_MyProc ?
in your package
Also note I think you set #SUB twice - I changed it to #BODY
Also please note it is usually a bad idea to store dates as varchar(250) - change it to date or datetime now if you have the opportunity.
CREATE PROC p_MyProc
#PackageStartTime Varchar(250)
AS
IF(SELECT COUNT(*)
FROM [dbo].[Table1] WHERE RowCDate >=#PackageStartTime)>0
BEGIN
DECLARE #SUB Varchar(250)
SET #SUB = 'File Failed'+##SERVERNAME
DECLARE #BODY Varchar(250)
SET #BODY = 'File Failed'+##SERVERNAME
EXEC sp_send_dbmail #profile_name='default',
#recipients='dev#null.com',
#subject=#SUB,
#body=#BODY,
#query= 'SELECT DISTINCT FileLoadName
FROM [dbo].[Table1] WHERE RowCDate >=#PackageStartTime',
#attach_query_result_as_file=1
GO
To move this into SSIS (please note I do not have access to SSIS so I'm flying blind)
Create an execute SQL Task with this in it:
SELECT COUNT(*) As RCount, 'File Failed' + ##SERVERNAME As Msg
FROM [dbo].[Table1] WHERE RowCDate >= ?
Pass your parameter in, and capture the result into two variables, (single row returned)
Your next step is another execute SQL Task, calling sp_send_dbmail with your variables. This is called conditionally so it only runs if the prior step returned a non zero value

Assigning function result to SQL variable and displaying

Migrating asp.net code (VB.net) to use functions and subroutines as parameters.
Using MS Server Management Studio to create said functions and subs.
Would like to test the functions from within MS SMS before testing them via the web page.
Here's an example. Say I have a function called "dbo.getNumber"
I'm trying to test it using the following:
USE [someDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
declare #value int;
select #value = dbo.getNumber;
print #value;
go
When I type F5 (to run the "query") it gives the following msg:
"The name "dbo.getNumber" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted."
The function dbo.getNumber was accepted just fine, btw. (It's counting records of a database that meet certain criteria.)
Hopefully you can infer from the non-working code what I am trying to do.
How can I print the value of a function (for testing purposes) from within SMS?
Correct solution as per James Johnson, below:
USE [someDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
declare #value int;
select #value = dbo.getNumber();
print #value;
go
Note the parens for the function invocation.
Note also: intellisense in SMS underlines dbo.getNumber() as if it were an error, but running the query with F5 works and outputs the right result.
You need to call it like this:
select #value = dbo.getNumber()

could any one help me finding the Error with SP

create function Fun12(#InsCd varchar)
returns varchar(100)
as
begin
declare #ret varchar(52)
set #ret = (select [InsName] from [Assignment4].[dbo].[1466]
where rtrim(ltrim([InsCd]))= #InsCd)
return #ret
end
Executing:
declare #r varchar(50)
exec #r = dbo.Fun12 '436'
select #r
I am getting NULL value.
Could any one please help me finding the error?
You need to specify a size for your parameter #InsCd.
Some thing like this but you might want to use another value than 20 depending on the size of field InsCd.
create function Fun12(#InsCd varchar(20))
First, you should make sure that the code contained by the function actually returns something when you run it directly in SQL Server Management Studio (SSMS):
-- SQL
select InsName from [1466] where rtrim(ltrim([InsCd])) = '436';
In this case, I would use a stored procedure rather than a function. You could also use the SSMS Profiler (Tools > Profiler) to monitor the traffic to SQL Server. This way, you can actually see what gets executed, see the parameters for SPs, etc.

Does SQL Server Management Studio (or SQL Server) evaluate *all* expressions?

Here's my configuration:
I have a re-runnable batch script that I use to update my database.
Inside of that batch script, I have code that says the following:
If Table 'A' doesn't exist, then create Table 'A' and insert rows into it.
Later on in that batch script, I create an schemabound indexed view on that table.
And if you didn't already know, indexed views require specific client settings.
Sometimes, when I re-run the script, that is after the table has been created, SQL Server Management Studio evaluates the "insert rows" code, which is protected by the 'If this table doesn't exist' code, and yields the following error:
Msg 1934, Level 16, State 1, Line 15
INSERT failed because the following SET options have incorrect settings: 'CONCAT_NULL_YIELDS_NULL, ANSI_WARNINGS, ANSI_PADDING, ARITHABORT'. Verify that SET options are correct for use with indexed views and/or indexes on computed columns and/or filtered indexes and/or query notifications and/or XML data type methods and/or spatial index operations.
Please note: If someone were to try this INSERT statement in a vacuum, I would fully expect SSMS to generate this error.
But not when it's protected by a conditional block.
My Question:
Does the SSMS compiler evaluate all expressions, regardless of whether they will actually be executed?
Yes, it evaluates all of them,take a look at this
declare #i int
select #i =1
if #i = 1
begin
declare #i2 int
set #i2 = 5
end
else
begin
declare #i2 int
set #i2 = 5
end
Msg 134, Level 15, State 1, Line 12
The variable name '#i2' has already been declared. Variable names must be unique within a query batch or stored procedure.
Another example with temp tables is here: What is deferred name resolution and why do you need to care?
your only way out would be to wrap it inside dynamic SQL
Note that most of the settings you mention are connection-level, i.e. in case you set/change them they stay in effect unless you close the connection or explicitly change their value.
Returning to your question. The error you mention looks like runtime error, i.e. the INSERT is actually being executed. It would be better if you could show your script (omitting details, but keeping batches).
Edit: it is not SSMS compiler that evaluates SQL you try to execute - it is SQL Server. What do you meant by 'evaluate'? Is it 'execute'? When you run a batch (which is what actually is being executed by a server), SQL Server first does syntactic analysis and throws error in case it finds any syntactic error, nothing is being executed at this point of time. In case syntax is ok, the server starts executing you batch.
Again, the error you show seems to be runtime - so I guess you'd carefully watch for the conditions and track what happens (or provide us more details about 'sometimes').