I don't think that the following error is the real issue.
Incorrect syntax near ')'.
The query parser was not able to parse the query because you have added a minus sign before the question mark ?
. In this answer i will try to clarify the main cause of the error you are seeing.
Parameter data type vs Variable data type
Based on the official OLEDB Source - Documentation:
The parameters are mapped to variables that provide the parameter values at run time. The variables are typically user-defined variables, although you can also use the system variables that Integration Services provides. If you use user-defined variables, make sure that you set the data type to a type that is compatible with the data type of the column that the mapped parameter references.
This implies that the parameter datatype is not related to the variable data type.
So when you are using -?
inside the SQL Command the query parser are not able to identify the parameter metadata even if it is mapped to an integer variable.
You can check my answer on the link below, it contains much details with experiments:
Solving the problem
(1) Force parameter data type
Try using CAST()
function to force the parameter data type and assign it to a variable in the same way you have declared @dt
:
DECLARE @interval INT = CAST(? as INT)
--If you want to get a negative number else ignore the row below
SET @interval = -1 * @interval
DECLARE @dt DATETIMEOFFSET = SWITCHOFFSET(CONVERT(DATETIMEOFFSET,GETDATE()),'-04:00');
DECLARE @DATE_OPG DATE;
SELECT @DATE_OPG = DWH_PR_DATEO
FROM TableName
WHERE YEAR(DWH_PR_DATO) = YEAR(DATEADD(MONTH,@interval ,@dt)) AND
MONTH(DWH_PR_DATO) = MONTH(DATEADD(MONTH,@interval ,@dt))
ORDER BY DWH_PR_DATO DESC
(2) Using Expressions
You can use Expressions while building the SQL Command:
- Add a variable of type string (Example:
@[User::strQuery]
)
Define an Expression within this variable:
"DECLARE @dt DATETIMEOFFSET = SWITCHOFFSET(CONVERT(DATETIMEOFFSET,GETDATE()),'-04:00');
DECLARE @DATE_OPG DATE;
SELECT @DATE_OPG = DWH_PR_DATEO
FROM TableName
WHERE YEAR(DWH_PR_DATO) = YEAR(DATEADD(MONTH,-" + @[User::KOERSEL] + ",@dt)) AND
MONTH(DWH_PR_DATO) = MONTH(DATEADD(MONTH,-" + @[User::KOERSEL] + ",@dt))
ORDER BY DWH_PR_DATO DESC"
In the OLEDB Source choose SQL Command from variable and Select @[User::strQuery]
Experiments
I tried a similar query using the AdventureWorks database:
DECLARE @dt DATETIMEOFFSET = SWITCHOFFSET(CONVERT(DATETIMEOFFSET, GETDATE()), '-04:00')
DECLARE @interval INT = CAST(? as INT)
SET @interval = -1 * @interval
DECLARE @DATE_OPG DATE
SELECT @DATE_OPG = A.[ModifiedDate]
FROM [AdventureWorks2016CTP3].[HumanResources].[Employee] AS A
WHERE YEAR(A.[ModifiedDate])=YEAR(DATEADD(MONTH,@interval,@dt)) AND
MONTH(A.[ModifiedDate])=MONTH(DATEADD(MONTH,@interval,@dt))
ORDER BY A.[ModifiedDate] DESC
SELECT * FROM [AdventureWorks2016CTP3].[HumanResources].[Employee]
WHERE [ModifiedDate] = @DATE_OPG
And the query is parsed successfully
