SSIS 2008 how to use EXEC - sql

Im using SSIS 2008
i want to try and run the following SQL code:
declare #test nvarchar(100)
set #test = 'Select Distinct Area From dbo.udf_RiskManagementPlan('') Where Area is not Null And Area != ''';
if exists (select object_id from sys.columns where object_id = object_id('dbo.udf_RiskManagementPlan') and name = 'Area')
exec sp_executesql #test
Else select Null As Area
It is working fine in SQL managment studio, but when i try and place it in OLEDB source i keep getting error regarding syntax
i tried placing the entire code in a variable value and just call that still gave same syntax error
i have feeling this has more to do with SSIS problem handling stored procedure and parameters then the syntax, but i cant seem find way around it

Actually in SSIS you can't put such expression in source. Split it into parts:
Put an SQL Task block with EXEC dbo.udf_RiskManagementPlan, set input/output parameters to get result (e.g. #SQLTaskResult)
On positive finish: set a variable Source_SQL to:
DTS.Variables["Source_SQL"].Value = 'Select Distinct Area From
'+DTS.Variables["SQLTaskResult"].Value+' Where Area is not Null And Area != ''
On error /no procedure or other error/ set Source_SQL to Else select Null As Area similar way. Double click the right connection, and set Value to Falure
Proceed to Data Flow - set OLE DB to read source sql dynamically from a variable in OLE DB Source Editor

Related

Execute SQL Task Error: Executing the query failed with the following error: "Incorrect syntax near ''."

I am working on a SSIS package that rejects already loaded files & load only new files to table.
I used for each loop and exceute SSQL to validate if the files are already loaded. When I evaluate
the expression of Execute SQL Task, it evaluates fine. But When I run the paackage I get the following error.
[Execute SQL Task] Error: Executing the query "DECLARE #FileName VARCHAR(100)
SET #FileName=Custo..." failed with the following error: "Incorrect syntax near ''.".
Possible failure reasons: Problems with the query, "ResultSet" property not set correctly,
parameters not set correctly, or connection not established correctly.
The Expression I used in the Execute SQL task is :
"DECLARE #FileName VARCHAR(100)
SET #FileName="+#[User::FileName]+"'
IF EXISTS (SELECT 1
FROM [dbo].[FileLoadStatus]
WHERE filename =#FileName)
BEGIN
SELECT 1 AS FileExistsFlg
END
ELSE
BEGIN
Select 0 AS FileExistsFlg
END"
screen shot of the execute SQL Task
I really apprecaite if you can tell where the problem is ?
You could simplify your expression a little bit to make clear where the SSIS variable is being used:
"SELECT COUNT(*) AS FileExistsFlg
FROM (
SELECT TOP(1) *
FROM
dbo.FileLoadStatus
WHERE
[filename] = '" + #[User::FileName] + "'
) x;"
On the other hand for the SQL Task you could use a standard parameterized query. Assuming you are using an OLEDB connection, the parameter placeholder is the ? sign. No expression is needed and the equivalent Direct Input for the task is:
SELECT COUNT(*) AS FileExistsFlg
FROM (
SELECT TOP(1) *
FROM
dbo.FileLoadStatus
WHERE
[filename] = ?
) x;
With OLEDB you have to map your variable to the placeholder by position (zero based) so in this case the Parameter Name is the number zero. The other properties depend on your metadata and correspond to the variable you would have declare in SQL...
This is less error prone, clearer and reusable for multiple calls as it generates a Prepared Statement.
If your connection type was ADO.Net, the mapping is name based. So check the documentation for the Parameter names and markers for each connection type.

How to count rows in SSIS based on specific conditions?

I have a Stored Procedure in SQL Server 2008 like below.
ALTER PROCEDURE myStoredProcedure
#Id int,
#hin varchar(30),
#checkValue varchar(30),
#CounterDeceasedPatients int=0 OUTPUT
insert into myTable
values (#Id, #hin, GETDATE())
if (#checkValue is not null)
BEGIN
set #CounterDeceasedPatients = #CounterDeceasedPatients + 1;
update myTable
set hin= #checkValue
where Id = #Id
RETURN;
END
I am calling this SP via SSIS, by using an OLE DB Command in Data Flow, which enables each rows in my file go to the SP - with the sql command: EXEC [dbo].[myStoredProcedure] ?,?,?. (The order of data (?) in my file is: Id, hin, checkValue)
What I want to do is to count how many different records (different rows) entered the if condition in my SP. SO I believe need to place a "row counter" somewhere, filtering its usage where #checkValue is not null. But I couldnt find it how. I am a newbie in SSIS, so I appreciate if someone helps me to figure this out. Thanks.
EDIT: I am trying to select only #checkValue as an input parameter for my ROW COUNT, but it is giving error:
EDIT2: I updated my SP. I added "CounterDeceasedPatients" variable as Int32 in SSIS and assigned it to 0. My sql execute command is: EXEC [dbo].[myStoredProcedure] ?,?,?,?,CounterDeceasedPatients
This is giving me the error:
Source: "Microsoft OLE DB Provider for SQL Server" Hresult:
0x80040E07 Description: "Error converting data type nvarchar to
int.".
When I use EXEC [dbo].[myStoredProcedure] ?,?,?,?,CounterDeceasedPatients output as SQL command, then I receive the error:
Description: "Cannot use the OUTPUT option when passing a constant to
a stored procedure.
I need help.
Use a script transformation and a DataFlow-level package variable.
Create the int-type variable with a default of 0, and in the script transformation, increment the variable if checkvalue is not null for the incoming row, and then use the value of the variable to set the value of your counter column.
Note that I am suggesting this INSTEAD of trying to update the counter with an OUTPUT variable in your stored procedure, and not as a way of trying to get that idea to work.

SQL Updating column after adding it giving "Invalid column name" error

I have the following SQL in SQL Server 2005 but I get an error stating "Invalid column name 'ExpIsLocalTime' (ln 7) when I run it:
IF NOT EXISTS(SELECT * FROM sys.columns WHERE Name = N'ExpIsLocalTime' AND Object_ID = Object_ID(N'[dbo].[tbl_SessionsAvailable]'))
BEGIN
ALTER TABLE dbo.tbl_SessionsAvailable ADD
ExpIsLocalTime bit NOT NULL CONSTRAINT DF_tbl_SessionsAvailable_ExpIsLocalTime DEFAULT (0)
UPDATE dbo.tbl_SessionsAvailable
SET ExpIsLocalTime = 1
END
GO
This will be in a script file that may be run more than once so I'm trying to make sure the UPDATE only runs once. Is there something about BEGIN/END that delays the execution of the DDL statement?
Your SQL query to do the UPDATE refers to a column that has not yet been created. At compile time, SQL Server detects that the column does not exist, so it gives you the error "Invalid column name 'ExpIsLocalTime'".
In order to include the UPDATE in this query, you will need to encapsulate it in a dynamic SQL query. In other words, something like this:
IF NOT EXISTS(SELECT * FROM sys.columns WHERE Name = N'ExpIsLocalTime' AND Object_ID = Object_ID(N'[dbo].[tbl_SessionsAvailable]'))
BEGIN
ALTER TABLE dbo.tbl_SessionsAvailable ADD
ExpIsLocalTime bit NOT NULL CONSTRAINT DF_tbl_SessionsAvailable_ExpIsLocalTime DEFAULT (0)
DECLARE #SQL NVARCHAR(1000)
SELECT #SQL = N'UPDATE dbo.tbl_SessionsAvailable SET ExpIsLocalTime = 1'
EXEC sp_executesql #SQL
END
GO
We have the same issue in our SQL scripts that maintain tables. After a table is created, if we add a column to it later, we have to use dynamic SQL to avoid these compilation errors.
Another possibly simpler solution is using the GO statement after the Alter statement. This would send the DDL to the server. Then run the rest of your SQL. This should work if you are using sqlcmd osql or SSMS.

Can I use a variable as the value of the option AUDIT_GUID for the CREATE SERVER AUDIT statement?

I am trying to make the Audit_GUID value in the CREATE SERVER AUDIT command dynamic by using the NEWID() function in SQL. Below is my SQL script to do this:
USE [master]
GO
DECLARE #newGUID as uniqueidentifier
SET #newGUID = NEWID()
CREATE SERVER AUDIT Audit_Select_Queries -- Name of the Audit(unique for a Server)
TO FILE
( FILEPATH = N'XXXX' -- Folder to Store Audit Files at
,MAXSIZE = 0 MB -- 0 = UNLIMITED
,MAX_ROLLOVER_FILES = 2147483647 -- Max possible number of Files
,RESERVE_DISK_SPACE = OFF
)
WITH
( QUEUE_DELAY = 1000 -- Delay Audit actions by this time for completion
,ON_FAILURE = CONTINUE -- Database operation is more important than Audit
,AUDIT_GUID = #newGUID -- UUID of the Audit (unique for a server)
)
ALTER SERVER AUDIT Audit_Select_Queries WITH (STATE = OFF)
GO
But I get a syntax error near #newGUID saying "Incorrect syntax near '#newGUID'"
Please let me know what am I doing wrong.
EDIT: I am working on Microsoft SQL Server 2012
No ...
CREATE SERVER AUDIT is a statement – so AUDIT_GUID isn't a 'parameter' in the same way that a SQL Server parameter of a stored procedure is a parameter. If you're familiar with other languages, you could consider CREATE SERVER AUDIT as a 'special form' and, as such, you simply need to remember that it doesn't accept variables for that option.
I can understand why that's confusing as, for example, the BACKUP statement(s) do allow variables for certain 'parameters' ("options"), namely the name of the database; e.g. this is perfectly valid T-SQL:
DECLARE #databaseName nvarchar = "insert_name_of_database_here";
BACKUP DATABASE databaseName
...
For clarifying these types of questions, just consult Microsoft's documentation for the relevant version of SQL Server if you can't remember whether some parameters or options accept variables or not. [You can easily open the relevant documentation from SSMS by highlighting the statement, built-in procedure, etc. and hitting F1 on your keyboard.]
But if You're Willing to Dynamically Generate the T-SQL ...
Here's how you can use dynamic SQL – via EXECUTE or sp_executesql – to do what you're trying to do:
DECLARE #dynamicSql nvarchar(1000);
SELECT #dynamicSql = 'CREATE SERVER AUDIT
...
AUDIT_GUID = ''' + CAST(#newGUID AS nvarchar(255)) + ''''
+ '...' + ...,
EXEC sp_executesql #dynamicSql;

Error in SQL stored procedure

I am getting the following error when I execute my stored procedure:
Msg 102, Level 15, State 1, Line 6Incorrect syntax near '2011'.(1 row(s) affected)
Here is the stored procedure:
ALTER PROCEDURE [dbo].[DeliveryFileNames]
AS
BEGIN
SET NOCOUNT ON;
declare #SQL nvarchar(4000)
Create Table #DelivTemp(
Style nvarchar(50),
Material nvarchar(50),
Filename nvarchar(100),
delivered_date date)
set #SQL=
N'insert into #DelivTemp
Select distinct Style,Material,filename
from OPENQUERY(GCS_PRODUCTION,
''SELECT LEFT(FILENAME,locate(''''_'''',FILENAME)-1)as Style,
substring_index(filename,''''_'''',2)as Material,filename,
delivered_date FROM view_delivery_log
where delivered_date > ''2011%'' order by Style '')'
exec (#SQL)
drop table dbo.DelivFN
Select * into dbo.DelivFN
from #DelivTemp
END
I am using OpenQuery to update a SQL table from a linked server on SQL Server 2008 R2.
I know that the underscore is a real issue, but I have tried a plethora of options including \, % and both single and double quotes.
Regardless I am getting the same result. I can run the query independently of the stored procedure and achieve the correct results. The filename field referenced several times is formatted 00000000_ABC4_A.png. I am using the underscore to identify the components of the file name that I need for my reporting purposes.
In addition to the the logical error of your date comparison using the % that the others have pointed out, your current issue is a syntactical error.
Since you've got a dynamic sql statement contained within another dynamic sql statement... you'll need to double-escape all of your single quotes... which you did in most of the query, except for the following line:
where delivered_date > ''2011%'' order by Style '')'
Properly escaped, would be:
where delivered_date > ''''2011%'''' order by Style '')'
Which raises the question... why are you building up the string to execute dynamically, instead of just calling the statement directly?
It's the syntax of ''2011%''. This is not a valid date. % being a wildcard means the compiler can't know what to compare against in the WHERE clause. You'd need to use an actual date: i.e. ''2011_01_01'' so the compiler can know what to compare against
I believe the stored proc exec runs under a different session, therefore you won't have access to the temp table anyway. So, it won't matter if you get that sql statement to run. You could always use YEAR(delivered_date) > 2011.
Another approach would be to use the fqn for the linked server to select into and bypass the temp table all together:
SELECT LEFT(FILENAME,locate('_',FILENAME)-1)as Style,
substring_index(filename,'_',2)as Material,filename,delivered_date
FROM [linked_server_name].[db_name].[dbo].view_delivery_log
into dbo.DelivFN