Execute SQL Task Editor: The query failed to parse. Syntax error, permission violation, or other nonspecific error.
Environment: SQL Server 2008 R2
Code:
CREATE TABLE dbo.PkgAudit
PkgAuditID INT IDENTITY(1, 1),
PackageName VARCHAR(100),
LoadTime DATETIME ,
NumberofRecords VARCHAR(50),
Status1 VARCHAR(50),
Status2 VARCHAR(50),
The following code is inserted in the SQL Task Execute Editor
INSERT INTO dbo.PkgAudit(PackageName
,LoadTime
,NumberofRecords
,Status1
,Status2
) VALUES(?,?,?,?,?)
Screen Shot (Parameter Mapping):
Problem: an error Message occurred when I hit Parse Query Button in the Execute SQL Task Editor, "Execute SQL: Task Editor: The query failed to parse. Syntax error, permission violation, or other nonspecific error". How I could Solve this
problem
Different connection providers require different Parameter syntax. E.g. ADO @ParameterName notatoin, not just an offset of 0,1 etc.
Arthur My Blog
Similar Messages
-
Using Union in Execute SQL Task
I am using the following SQL statement in an Excute SQL Task:
declare @RespAreaSubAreaID int, @UserLevelID int, @SubmittedByUserID int, @RespAreaID int, @SubAreaID int
Set @RespAreaSubAreaID = ?
Set @SubmittedByUserID = ?
Set @UserLevelID = ?
set @RespAreaID = ?
set @SubAreaID = ?
select users.User_EmailAddress + ';' As CC
from users inner join UserLevelsNotificationFrequencys on users.user_Id = UserLevelsNotificationFrequencys.User_id
where UserLevelID = @UserLevelID and RespAreaSubAreaID = @RespAreaSubAreaID and (NotificationFrequencyID = 4 and users.user_id <> @SubmittedByUserID)
union
select users.User_EmailAddress + ',' As CC
from users inner join UserLevelsNotificationFrequencys on users.user_Id = UserLevelsNotificationFrequencys.User_id
where UserLevelID = @UserLevelID and RespAreaSubAreaID = @RespAreaSubAreaID and (NotificationFrequencyID = 1)
I have my parameter mapped correctly. My results set is set to xml because I want it all in one string to use as a variable named User:CC. On the Result Set tab the result name is 0 and the variable name is User:CC. When I run my package I am getting
the error below. Can I not do a union query in the execute SQL task? I tried to not declare anything and just map to each of the variables that I am passing in the order that they are needed but that didn't work either. Thanks in advance for your help in this
matter.
[Execute SQL Task] Error: Executing the query "declare @RespAreaSubAreaID int, @NotificationID
in..." failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection
not established correctly.
Reach for the unknown!Thank you for your reply but I am not using the Data Flow. All my work is happening on the Control Flow. I am looping through a set of records and emailing them to the correct
people. Setting my result set to XML worked for the To Line (See my earlier post Execute SQL task for Email ToLine using COALESCE and two variables) and now I am working on the CC line which is more complicated because it uses a union statement.
Reach for the unknown! -
I am using the following query in Execute SQL Task
SELECT CASE(SELECT COUNT(*) FROM STG_APJ_APIW_DETAILS
WHERE source_filename = ?
AND lTRIM(RTRIM([BILLING DATE])) <> '') WHEN 0 THEN (SELECT CONVERT(VARCHAR(8), GETDATE(), 112) AS [YYYYMMDD])
ELSE
(SELECT TOP 1 [BILLING DATE] FROM STG_APJ_APIW_DETAILS
WHERE source_filename = ?
AND lTRIM(RTRIM([BILLING DATE])) <> '')
END
In parameter Mapping i have created two parameters and in result set i choose my variable.
Result set property is Single Row.
Following is the error message i received,
[Execute SQL Task] Error: Executing the query "SELECT CASE(SELECT COUNT(*) FROM STG_APJ_APIW_DETA..." failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems
with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
SarvanI cant see where you've named resultset. try like below to make sure resultset has the name used in resultset tab
SELECT CASE(SELECT COUNT(*) FROM STG_APJ_APIW_DETAILS
WHERE source_filename = ?
AND lTRIM(RTRIM([BILLING DATE])) <> '') WHEN 0 THEN (SELECT CONVERT(VARCHAR(8), GETDATE(), 112))
ELSE
(SELECT TOP 1 [BILLING DATE] FROM STG_APJ_APIW_DETAILS
WHERE source_filename = ?
AND lTRIM(RTRIM([BILLING DATE])) <> '')
END AS [Billing Date]
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Execute SQL task for Email ToLine using COALESCE and two variables
Hello...
I am converting an old DTS package to SSIS. The old package consist of mostly ActiveX Script so I am breaking it down into steps. Basically... I am retreving a set of records that need to be sent via email to multiple people. In my package to create
my ToLine for the Send Mail Task I am using several steps. Frist I am using:
SELECT CASE
WHEN EXISTS ( SELECT users.User_EmailAddress
FROM dbo.Errors INNER JOIN
dbo.Users ON users.user_id = Errors.MonitorAuditor_User_Id
WHERE ([Audit_Id] = ?) AND ([ErrorCode_Id] = ?) ) THEN
1
ELSE
0
END AS ValidEventID
I use this to see if there is any records to create my email string. This works fine. After this I have a Script Task that splits my pipe in two. When no records exist (User::ValidEventID == 0) I am loging that event to a log. When records do exist
I am using another Execute SQL task to create the actual ToLine:
Declare @combinedString VARCHAR(max)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + Users.User_EmailAddress
FROM dbo.Errors INNER JOIN
dbo.Users ON users.user_id = Errors.MonitorAuditor_User_Id
WHERE ([Audit_Id] = ?) AND ([ErrorCode_Id] = ?)
SELECT convert(varchar(4000),@combinedString) as StringValue
I have my resultSet set to Single Row. I have two variables coming if for the Audit_Id and ErrorCode_Id. My Result Set is set to a Variable: User::EmailAddressString.
Next it goes through a foreach loop to map to the ToLine email variable that I created named User:User_EmailAddress.
Then I am using that in my Send Email Task.
It all works fine when I hard code my variables into the COALESCE statement but as soon as I replace that with the ? that SSIS requires for variables I am getting the following error:
[Execute SQL Task] Error: Executing the query "Declare @combinedString VARCHAR(max)
SELECT ..." failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly,
parameters not set correctly, or connection not established correctly.
I have tried changing my resultset property, I have checked my paramenters and my connection. I don't understand why it works fine when I have my varaiables hard coded but not when I change them to the ?.
Thanks in advance for you help in this matter.
Reach for the unknown!Katherine... that did not work.
What I ended up doing was taking out the forloop all together. In my Execute SQL Task I changed the result set from single row to XML. I took out the COALESCE statement and just went for something more basic:
select users.User_EmailAddress + ';' as User_EmailAddress from Errors inner join users on users.user_id = Errors.MonitorAuditor_User_Id WHERE ([Audit_Id] = ? AND [ErrorCode_Id] = ?)
Currently I am just logging the string to a text file so I can see the results. In my text file the string is surrounded by <ROOT></ROOT>. So I will next I will work on triming that off the string and then populate my Send Mail Task.
This is how I trimed off the <ROOT></ROOT>:
Dts.Variables(
"EmailAddressString").Value = Replace(Dts.Variables("EmailAddressString").Value,
"<ROOT>",
Dts.Variables(
"EmailAddressString").Value = Replace(Dts.Variables("EmailAddressString").Value,
";</ROOT>",
Thanks again everyone for the help!
Reach for the unknown! -
I executed a simple query inside an execute SQL task -
SELECT col1, col2
from thetable
where code = ?
order by id asc
Exec sql task - ADO.NET connection
parameter "code" is an int32 in SSIS and int32 in parameter mapping of exec sql task.
It works fine in SQL server, but in SSIS it causes the error -
[Execute SQL Task] Error: Executing the query "SELECT col1, col2
from thet..." failed with the following error: "Failed to create an IDataAdapter object. This provider may not be fully supported with the Execute SQL Task. Error message 'Incorrect syntax near '?'.'.". Possible failure reasons: Problems with
the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
How do I fix this error ?Thanks. I think it was sqlclient. I changed it to OLEDB to avoid that issue. Btw, what is this "provider" ?
Hi blastoSO,
To check which provider is used by the current ADO.NET Connection Manager, you can open the “Configure ADO.NET Connection Manager” window, and check the “Managed Provider” option of each Data connection.
In an Execute SQL Task, if the managed provider is “System.Data.SqlClient”, we should use the rule for the ADO.NET connection type in the following table. If the managed provider is “System.Data.Oledb” or “System.Data.Odbc”, it actually uses the OLE DB provider
or ODBC provider, so we should use the rule for the OLE DB or OBC rule in the following table:
Reference:
http://technet.microsoft.com/en-us/library/cc280502.aspx
Regards,
Mike Yin
TechNet Community Support -
Hi there,
I have this issue with my Execute SQL Task Failing. I am trying to execute a sp using an execute sql task. The execute statement is contained in a variable (exec [sp_name] par1, par2) that I have declared at the package level. Now inside the exec sql
tak, I am calling this variable. Now when I try to execute this task, it fails and I get the following:
[Execute SQL Task] Error: Executing the query "EXEC CTL_ISRT_A 55,1" failed with the following error: "Could not find stored procedure 'CTL_ISRT_A'.". Possible failure reasons: Problems with the query, "ResultSet" property not
set correctly, parameters not set correctly, or connection not established correctly.
There is a stored procedure called "CTL_ISRT_A" in the db and I am able to execute it from SQL Server. This sp is inserting a new row in the table and it returns @@IDENTITY.
I tried setting the result set to a 'Single Row' and tried assigning the value to a variable but it didnt help. Could someone help me here?
Thanks in advancereturn it as an output parameter
ie make sp like below
ALTER PROCEDURE [devdba].[M_CTL_ISRT]
@F_ID INT
, @PR_IND BIT
, @Debug bit = 0
, @IDVal int = 0 OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE @ErrorMsg varchar(5000)
DECLARE @USR_ID AS INT = 1;
INSERT INTO TBL_D (F_ID, PR_IND, USR_ID,CRE_DT, LAST_MODD_USR_ID, LAST_MODD_DT)
VALUES (@F_ID, @PR_IND, @USR_ID, GETDATE(), @USR_ID, GETDATE())
SELECT @IDVal= @@IDENTITY
END
Then in execute sql task call it as
EXEC devdba].[M_CTL_ISRT] ?,?,0,? OUT
then in parameter tab pass required variables and for last parameter make direction as Output and you'll get identify value stored in it.
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Dynamically change the db and server in execute sql task
Pkg 2: Moves data from B_STG (Staging DB) to B_Det_STG (Staging DB) ---- option1
Pkg 3: Moves data from B_STG (Staging DB) to B_Det (PC DB) ---- option2
This part is duplicating in both the packages
So they want me to merge both of them into in execute sql task and dynamically change between option1 and option2 depending on a pkg level variable.
So, I create a pkg level variable called ExecutionVariable: 'ANALYSIS' or 'LOADING'
If 'ANALYSIS' it needs to do option1 else option2.
So, I ma trying to create a dynamic connection string in execute sql task.
I change the connection property in execute sql task editor dynamically my giving the expression: @[User::ExecutionVariable] == "ANALYSIS"? @[User::STAGINGDBConnectionString] : @[User::PCDBConnectionString]
which evaluates to : Data Source=AW-ETL-D1;Initial Catalog=Staging;Integrated Security=SSPI;Provider=sqloledb
But when I run the sql task, its giving me an error:
ERROR:
TITLE: Microsoft Visual Studio
Nonfatal errors occurred while saving the package:
Error at PC_DataLoad: The connection "Data Source=AW-ETL-D1;Initial Catalog=Staging;Integrated Security=SSPI;Provider=sqloledb" is not found. This error is thrown by Connections collection when the specific connection element is not found.
Error at PC_DataLoad: The connection "Data Source=AW-ETL-D1;Initial Catalog=Staging;Integrated Security=SSPI;Provider=sqloledb" is not found. This error is thrown by Connections collection when the specific connection element is not found.
Can u please help me.Hi ,
Don't try to make the "Execute Sql" task as dynamic.
Try to make OLEDB connection Manager as "Dynamic".
Steps:
1. Create OLE DB Connection pointing to any database then set expression to connection string variables like below.
Provider=SQLNCLI10.1;Integrated Security=SSPI;Initial Catalog=YourDBname;Data Source=YourServerName.
2. Make Delayed Validation property to "True".
3. Set the created dynamic OLE DB connection to your Execute SQL task.
4. Change the connection string variable accordingly before running the "Execute SQL" task.
Hope it will help you.
Regards,
Nandhu -
Question:
There is a scenario that users want to send multiple rows returned by Execute SQL Task as Email content to send to someone. With Execute SQL Task, the Full result set is used when the query returns multiple rows, it must map to a variable of the Object data
type, then the return result is a rowset object, so we cannot directly send the result variable as Email content. Is there a way that we can extract the table row values that are stored in the Object variable as Email content to send to someone?
Answer:
To achieve this requirement, we can use a Foreach Loop container to extract the table row values that are stored in the Object variable into package variables, then use a Script Task to write the data stored in packages variables to a variable, and then set
the variable as MessageSource in the Send Mail Task.
Add four variables in the package as below:
Double-click the Execute SQL Task to open the Execute SQL Task Editor, then change the ResultSet property to “Full result set”. Assuming that the SQL Statement like below:
SELECT Category, CntRecords
FROM [table_name]
In the Result Set pane, add a result like below (please note that we must use 0 as the result set name when the result set type is Full result set):
Drag a Foreach Loop Container connects to the Execute SQL Task.
Double-click the Foreach Loop Container to open the Foreach Loop Editor, in the Collection tab, change the Enumerator to Foreach ADO Enumerator, then select User:result as ADO object source variable.
Click the Variable Mappings pane, add two Variables as below:
Drag a Script Task within the Foreach Loop Container.
The C# code that can be used only in SSIS 2008 and above in Script Task as below:
public void Main()
// TODO: Add your code here
Variables varCollection = null;
string message = string.Empty;
Dts.VariableDispenser.LockForWrite("User::Message");
Dts.VariableDispenser.LockForWrite("User::Category");
Dts.VariableDispenser.LockForWrite("User::CntRecords");
Dts.VariableDispenser.GetVariables(ref varCollection);
//Format the query result with tab delimiters
message = string.Format("{0}\t{1}\n",
varCollection["User::Category"].Value,
varCollection["User::CntRecords"].Value
varCollection["User::Message"].Value = varCollection["User::Message"].Value + message;
Dts.TaskResult = (int)ScriptResults.Success;
The VB code that can be used only in SSIS 2005 and above in Script Task as below, please note that in SSIS 2005, we should
change PrecompileScriptIntoBinaryCode property to False and Run64BitRuntime property to False
Public Sub Main()
' Add your code here
Dim varCollection As Variables = Nothing
Dim message As String = String.Empty
Dts.VariableDispenser.LockForWrite("User::Message")
Dts.VariableDispenser.LockForWrite("User::Category")
Dts.VariableDispenser.LockForWrite("User::CntRecords")
Dts.VariableDispenser.GetVariables(varCollection)
'Format the query result with tab delimiters
message = String.Format("{0}" & vbTab & "{1}" & vbLf, varCollection("User::Category").Value, varCollection("User::CntRecords").Value)
varCollection("User::Message").Value = DirectCast(varCollection("User::Message").Value,String) + message
Dts.TaskResult = ScriptResults.Success
End Sub
Drag Send Mail Task to Control Flow pane and connect it to Foreach Loop Container.
Double-click the Send Mail Task to specify the appropriate settings, then in the Expressions tab, use the Message variable as the MessageSource Property as below:
The final design surface like below:
References:
Result Sets in the Execute SQL Task
Applies to:
Integration Services 2005
Integration Services 2008
Integration Services 2008 R2
Integration Services 2012
Integration Services 2014
Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.Thanks,
Is this a supported scenario, or does it use unsupported features?
For example, can we call exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='b64ce7ec-d598-45cd-bbc2-ea202e0c129d'
in a supported way?
Thanks! Josh -
SQL Server 2008 Execute SQL Task parameter problem
hi, guys
i create a very simply package which only Execute SQL task, set the properties as:
the testing table structure:
create table t(
idx int,
cname varchar(60)
Execute SQL Task setting:
[genaral]
ResultSet: None
ConnectionType: Ado.net
connection:LocalHost.APR11.sa1
SQLsourceType:Direct input
SQLStatement:delete from t where idx=?
[parameter mapping]
variable name: user::idx
direction: input
data type: Int32
parameter name:NewParameterName
parameter size:-1
i hardcode the idx=1, but get error:
SSIS package "test.dtsx" starting.
Error: 0xC002F210 at Execute SQL Task, Execute SQL Task: Executing the query "delete from t where idx=?" failed with the following error: "Parameter name is unrecognized.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Execute SQL Task
SSIS package "test.dtsx" finished: Success.
help me please.
Regards.Hello,
Here you go
http://decipherinfosys.wordpress.com/2008/03/26/running-parameterized-sql-commands-using-the-execute-sql-task-i/
http://technet.microsoft.com/en-us/library/ms140355.aspx
if you use ADO.NET then the way Execute SQL task take parameter is different then "?".... you have to use @paramter.. Please check the above link
Thanks
http://sqlage.blogspot.com/ -
Execute SQL Task with Parameter - from DB2 to SQL Server
I am pulling data from DB2 to SQL Server.
1st Execute SQL task runs the following against DB2:
SELECT TIMESTAMP(CHAR(CURRENT_DATE - (DAY(CURRENT_DATE)-1) DAYS - 1 MONTH)) as START_MONTH
FROM SYSIBM.SYSDUMMY1;
I'm storing it as a Result Set.
Next I have a Data Flow Task. This pulls data from DB2 where the date matches the parameter.
FROM SCHEMA.TABLE t
WHERE DATE_TIME_COLUMN= ?
This works fine. Guessing, because the parameter source is DB2 and the Data Flow source is DB2.
The problem is, I want to remove existing data for the same date in the SQL table. IE, if I'm pulling March 2014 data from DB2, I want to be sure there is no March 2014 data in the SQL table. The main use is for re-runs.
So, I added another Execute SQL task after the first one that assigns the variable, and before the Data Flow Task. This runs the following statement against SQL Server:
DELETE FROM
database.dbo.table
WHERE DATE_TIME_FIELD >= ?
The package fails at the new Execute SQL Task with the following error message:
Error: 0xC002F210 at Execute SQL Task, Execute SQL Task: Executing the query "DELETE FROM
SBO.dbo.tblHE_MSP_FEE_BUCKETS
WHERE T..." failed with the following error: "Parameter name is unrecognized.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established
correctly.
Task failed: Execute SQL Task
SSIS package "Load_MSP_Fee_Buckets_SQL.dtsx" finished: Success.
The program '[14240] Load_MSP_Fee_Buckets_SQL.dtsx: DTS' has exited with code 0 (0x0).
I am assuming this is something to do with the Parameter source being DB2, and trying to use against SQL?
Any suggestions on how to make this work??
Thanks,
-Al HParameter name is unrecognized
is the key, how come DB2 is related if it runs against SQL Server
What I think is happening you do not use the OLEDB connection to SQL Server.
Likewise, if it is ADO then the query needs to be
DELETE FROM
database.dbo.table
WHERE DATE_TIME_FIELD >= @MyDate
Arthur My Blog -
SSIS Execute SQL Task using sp_rename giving deadlock issues
All,
We have a job that has 2 steps and both of those steps call an SSIS package
1st package - Loads the data from a SQL server source, to a SQL Server destination tables, say, "TblHistory" is one of them
2nd package - It does a re-name from the History table to the Main table, so below, is how the code looks like in the execute SQL Task:
BEGIN TRANSACTION
EXECUTE sp_rename 'dbo.Tbl', 'TblOld'
EXECUTE sp_rename N'dbo.TblOld.PK_TblId', N'PK_TblIdOld', N'INDEX'
EXECUTE sp_rename 'dbo.TblHistory', 'Tbl'
EXECUTE sp_rename N'dbo.Tbl.PK_TblHistoryId', N'PK_TblId', N'INDEX'
EXECUTE sp_rename 'dbo.TblOld', 'TblHistory'
EXECUTE sp_rename N'dbo.TblHistory.PK_TblIdOld', N'PK_TblHistoryId', N'INDEX'
COMMIT TRANSACTION
In package 1 there are multiple history tables that are being loaded and most of them get renamed in the 2nd package. There is a separate SQL task for each of the history tables. The problem that I am running in to are the deadlock issues. When the 2nd package
runs, it throws this error:
"SQL - Table Rename & Swap for "Tbl" Execute SQL Task Description: Executing the query "BEGIN TRANSACTION EXECUTE sp_rename Tbl..." failed with the following error: "Transaction
(Process ID 60) was deadlocked on lock resources with another process and has been chosen as the deadlock victim."
It's giving me a deadlock issue on the other tasks as well. So, when the job ran today, I am noticing 4 deadlock errors on the 4 different execute SQL tasks in the 2nd package (i.e. the job fails at 2nd step)
Has anyone faced this scenario before?Why renaming tables? The data do not change. So just load the data to an interim table and push it to the target or may be you do not need it at all - just load the right table.
I admit I fail to capture the overall picture of what you are trying to solve or deliver. But renaming tables is something not usual.
Arthur My Blog -
SSIS - Using Variables in Execute SQL Task Error
The following query in my Execute SQL Task throws the following error when run - [Execute SQL Task] Error: Executing the query "SELECT @columnz = COALESCE(@columnz + ',[' + times..." failed with the following error:
"Must declare the scalar variable "@columnz".". Possible failure reasons: Problems with the query,
"ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Query:
drop table tmpNCPCNCDownstreamMaxUtilization3wks
select node, max(utilization) as max_Utilization, DATE
into tmpNCPCNCDownstreamMaxUtilization3wks
from stage_ncpcncdownstream_temporal
WHERE Date BETWEEN DATEADD(day, -20, GETDATE()) AND GETDATE()
group by node, date
order by node
go
alter table tmpNCPCNCDownstreamMaxUtilization3wks add Timestamp varchar(50)
go
update tmpNCPCNCDownstreamMaxUtilization3wks
set Timestamp = 'WeekOf_' + cast(left(Date, 11) as varchar)
go
--drop table tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--go
declare @columnz varchar (8000)
go
SELECT @columnz = COALESCE(@columnz + ',[' + timestamp + ']','[' + timestamp+ ']')
FROM tmpNCPCNCDownstreamMaxUtilization3wks group by timestamp order by timestamp
go
--pivot contents in @columns
declare @query varchar(8000)
SET @query ='select * into tmpNCPCNC_DownstreamNodeUtilizationMaxPivot from
(select node, timestamp, Max_Utilization from tmpNCPCNCDownstreamMaxUtilization3wks)a
pivot
sum(max_Utilization) for timestamp in('+ @columnz +')
)as p'
execute (@query)
--empty contents from NCPCNCDownstreamMaxUtilization3wks
update tmpNCPCNCDownstreamMaxUtilization3wks
set timestamp =''
truncate table tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
--load to table to be joined to Node feature class
insert into tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
(Node, TwoWeeksAgo, PreviousWeek, CurrentWeek)
select * from tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--calculate average utilization for all values in each record
update tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
set average = (coalesce(twoweeksago, 0) + coalesce(previousweek, 0) + coalesce(currentweek, 0))/3
from tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
ScottIssue is with variable @columnz.
Scope of variables is only limited to the batch and if batch is over Variable is no more accessible.
Reproduce Steps:
DECLARE @columnz int = 0
Go --Scope of @columnz ends here
SELECT @columnz -- Ends up with error
So you have to remove GO keyword. I have commented 2 of them in below:
DROP TABLE tmpNCPCNCDownstreamMaxUtilization3wks
SELECT node
,max(utilization) AS max_Utilization
,DATE
INTO tmpNCPCNCDownstreamMaxUtilization3wks
FROM stage_ncpcncdownstream_temporal
WHERE DATE BETWEEN DATEADD(day, - 20, GETDATE())
AND GETDATE()
GROUP BY node
,DATE
ORDER BY node
GO
ALTER TABLE tmpNCPCNCDownstreamMaxUtilization3wks ADD TIMESTAMP VARCHAR(50)
GO
UPDATE tmpNCPCNCDownstreamMaxUtilization3wks
SET TIMESTAMP = 'WeekOf_' + cast(left(DATE, 11) AS VARCHAR)
GO
--drop table tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--go
DECLARE @columnz VARCHAR(8000)
--GO
SELECT @columnz = COALESCE(@columnz + ',[' + TIMESTAMP + ']', '[' + TIMESTAMP + ']')
FROM tmpNCPCNCDownstreamMaxUtilization3wks
GROUP BY TIMESTAMP
ORDER BY TIMESTAMP
--GO
--pivot contents in @columns
DECLARE @query VARCHAR(8000)
SET @query = 'select * into tmpNCPCNC_DownstreamNodeUtilizationMaxPivot from
(select node, timestamp, Max_Utilization from tmpNCPCNCDownstreamMaxUtilization3wks)a
pivot
sum(max_Utilization) for timestamp in(' + @columnz + ')
)as p'
EXECUTE (@query)
--empty contents from NCPCNCDownstreamMaxUtilization3wks
UPDATE tmpNCPCNCDownstreamMaxUtilization3wks
SET TIMESTAMP = ''
TRUNCATE TABLE tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
--load to table to be joined to Node feature class
INSERT INTO tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week (
Node
,TwoWeeksAgo
,PreviousWeek
,CurrentWeek
SELECT *
FROM tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--calculate average utilization for all values in each record
UPDATE tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
SET average = (coalesce(twoweeksago, 0) + coalesce(previousweek, 0) + coalesce(currentweek, 0)) / 3
FROM tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
-Vaibhav Chaudhari -
Execute SQl Task Error SSIS Package
Hi all,
I`m using for each loop container in my package to grab the file name from the source path. I have created 2 vairables
FilePath and SourceFolder
I`m using execute sql task inside the container and this is my query
Insert into [dbo].[DCA_FF_TEST] (File_Name,File_Date) SELECT File_name = ?,
File_Date = GetDate()
Please not the Table I am trying to insert has more columns but at this stage I dont need them.
When i execute the task I get an error
[Execute SQL Task] Error: Executing the query "
INSERT INTO [dbo].[DCA_FF_TEST] ([File_Name],[F..." failed with the following error: "The statement has been terminated.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters
not set correctly, or connection not established correctly.
Can someone point me in the right direction? Am I missing anything?
Resultset property Set to None
Parameter Mapping: Variablename: FilePath , Direction: Input, datatype : Varchar, Parametername: 0, ParameterSize: 100.
I`ve checked the connection as well it works.
FMDid you try
Insert into [dbo].[DCA_FF_TEST] (File_Name,File_Date)
SELECT ?, GetDate()
Or
Insert into [dbo].[DCA_FF_TEST] (File_Name,File_Date) VALUES (?, GetDate())
A Fan of SSIS, SSRS and SSAS -
Customized Execute SQL Task in SSIS
Hi,
I,m using Execute SQL Task in SSIS Package with these configuration ..
But, If SQL Statement doesn't report any record mean Query is not returning any data then this Task will be failed.
How can I assure that If there is no record is returning in query that " Execute SQL Task " should bot be executed .
Also I If I can do the same thing through other methods in SSIS, Pls response .
-AshishHi Ashish,
The Execute SQL Task failed because you had set the ResultSet to “Single row”, however, the SQLStatement didn’t return any records. If you don’t want to execute this task when the query doesn’t return any records, you can use the following method:
Create a String type variable RowCnt, add another Execute SQL Task prior to this task.
In the new Execute SQL Task, input the SQLStatement as “Select Count(*) From Table”, set the ResultSet to “Single row”, and map the result set 0 to the variable RowCnt.
Join the two tasks (green line), and edit the Precedence Constraint (Green line), and set the expression to “(DT_I4)@[User::RowCnt]>0”.
Regards,
Mike Yin
TechNet Community Support -
I am experiencing an unexplainable behavior with the Execute SQL Task control in SSIS 2012. The following is a description of how to simulate
the issue I will attempt to describe:
1. Create a package and add two variables User::varTest1 and User::varTest2 both of String type with default value of "Select GetDate()"
for each, have shown this to not matter as the same behavior occurs when using a fixed string value or empty string value.
2. Add a new Execute SQL Task to the control flow.
3. Configure an OLE DB connection.
4. Set SQLSourceType = "Direct Input"
5. Set the ResultSet property of the task to "Single Row"
6. In the ResultSet tab add two results as follows:
Result Name: returnvalue1, Variable Name: User::varTest1
Result Name: returnvalue2, Variable Name: User::varTest2
7. Set an expression for the SqlStatementSource property with a string value of "Select 'Test' returnvalue1, 'Testing' returnvalue2'"
The idea is that the source would be dynamically set in order to run a t-sql statement which would have dynamic values for database name
or object that would be created at runtime and then executed to set the user variable values from its resultset. Instead what occurs is that a DBNull error occurs.
I am not sure if anyone else has experienced this behavior performing similiar actions with the Execute SQL Task or not. Any help would be
appreciated. The exact message is as follows:
[Execute SQL Task] Error: An error occurred while assigning a value to variable "varRestoreScript": "The type of the value
(DBNull) being assigned to variable "User::varRestoreScript" differs from the current variable type (String). Variables may not change type during execution. Variable types are strict, except for variables of type Object.
User::varRestoreScript is the first return value. And even with the a dummy select the same result occurs. I have narrowed the issue down
to the T-SQL Statement structure itself.
The following works just fine within the execute sql task control as long as no resultset is configured for return:
"Declare @dynamicSQL nvarchar(max)
Select @dynamicSQL = name
From sys.databases
Where name = 'master'
Select atest_var1=@dynamicSQL, atest_var2='static'"
I have tried various iterations of the script above with no success. However, if I use the following derivative of it the task completes
successfully and variables are set as expected. This will not work for my scenario however as I need to dynamically build a string spanning multiple resultsets to build one of the variable values.
"Select atest_var1=name, atest_var2='static'
From sys.databases
Where name = 'master'
I have a sample package which can reproduce this issue using the above code. You can get to that through the post on www.sqlservercentral.com/Forums/Topic1582670-364-1.aspx
ScottArthur, the query when executed doesn't return a null value for the @dynamicSQL variable. It returns "master" as a string value. Even the following fails which implements that suggestion:
Declare @dynamicSQL as nvarchar(max)
Select @dynamicSQL = name
From master.sys.databases
Where name = 'master' -- (or any other DB name)
I believe I have found the cause of the issue. It is datatype and size related. The above script will properly set the variables in the resultset as long as you don't use nvarchar(max) or varchar(max). This makes the maximum data size for
a String variable 4000 characters whether unicode or non-unicode typed.
Maybe you are looking for
-
Firefox does not open, says it's running when trying to restart, but does not show up
Cannot get Firefox to visibly run. Will not open in safe mode and will not close (says its running when I attempt to shutdown or restart computer. Have uninstalled Firefox and reinstalled 8.0 several times and nothing has changed. Have scanned , defr
-
Downloading of file[SocketException]
hi... im encountering an exception whenever i click the cancel button on downloading of file but when i click open the program runs good... here's the stackTrace [5/23/07 14:47:20:859 CST] 17dd17dd SystemErr R java.net.SocketException: Connection res
-
Unable to open URL from SMS message
When I receive any SMS with link and when I click on that link the default browser opens and closes. I am not able to open any link. Due to this I have to always copy the link and paste in the browser and then try to open. I have changed default brow
-
In sq00 we have a number or queries created by one of our consultants who no longer is working for us. The problem with this is that all of the variants that she created are protected. I found a similiar post and have tried the following things to
-
Extension development question
Hello! How can I use for example standard „Select Connection" dialog in my own extension development? Is it allowed? Or should I create my own? Regards, Alexandre S.