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

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.

Related

Problem with Stored Procedures in PHPmyAdmin

Attempting to perform operations with a random integer in SQL.
The following code works perfectly as intended when run as pure SQL, but triggers a syntax error when attempting to save it into a stored procedure.
SET #sample_count = (SELECT count(*)
FROM cinder_sample);
SELECT #sample_count;
SET #random_ID = (SELECT FLOOR(RAND()*#sample_count));
SELECT #random_ID;
Any ideas as to what could be going wrong?
The exact error triggered is:
"The following query has failed: "CREATE DEFINER=root#localhost PROCEDURE play_random_sp() NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER DELIMITER // SET #sample_count = (SELECT count() FROM cinder_sample)// SELECT #sample_count// SET #random_ID = (SELECT FLOOR(RAND()#sample_count))// SELECT #random_ID"
MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '// SET #sample_count = (SELECT count(*) FROM cinder_sample)// SELECT' at line 1"

SQLRPGLE syntax for Exec sql from a varying length variable?

On IBMi (database is DB2 for i) in SQLRPGLE I have a program that builds a large SQL statement into a variable that I would like to run.
When I try to run it as a variable I receive a token error
Some background
Here is an example that works because it does not use a variable
Exec SQL
Create table MyLib/MyFile as(select * from XXLIB/XXFILE)
DATA INITIALLY DEFERRED REFRESH DEFERRED
maintained by user;
When I save this in a variable like #SQLStm and then try to execute as SQL
Exec SQL
:#SQLStm;
I get the error
Token : was not valid. Valid tokens: .
Also I am open to different approaches
https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_71/cl/runsqlstm.htm
Like RUNSQLSTM SRCFILE(MYLIB/MYFILE) SRCMBR(MYMBR)
Maybe there is a way to take a variable and save it to a source member?
Then use RUNSQLSTM over the source member
Showing some code:
Definition for the variable
d #SQLStm s A Len(6144) Varying(4)
Even when trying a portion of the SQL statement as a variable
#SQLStm = select * from XXLIB/XXFILE;
and then try:
Exec SQL
Create table MyLib/MyFile as( :#SQLStm)
DATA INITIALLY DEFERRED REFRESH DEFERRED
maintained by user;
I get the error
Token : was not valid. Valid tokens: .
I expect the SQLRPLE to compile
Instead of SQL precompile failed.
MSG ID SEV RECORD TEXT
SQL0104 30 236 Position 31 Token : was not valid. Valid tokens:
.
Message Summary
Total Info Warning Error Severe Terminal
1 0 0 0 1 0
30 level severity errors found in source
This is static SQL
Exec SQL
Create table MyLib/MyFile as(select * from XXLIB/XXFILE)
DATA INITIALLY DEFERRED REFRESH DEFERRED
maintained by user;
What you want is dynamic SQL
wSqlStmt = 'Create table MyLib/MyFile as(select * from XXLIB/XXFILE)'
+ ' DATA INITIALLY DEFERRED REFRESH DEFERRED'
+ ' maintained by user';
exec SQL
execute immediate :wSqlStmt;
Note that some statements can't be execute immediate instead you have to prepare then execute them.
more information can be found in the Embedded SQL programming manual.

error: too many many input arguments matlab

I am trying to execute a Sql query in matlab. The sql uses 'select' command for selecting a particular row using a columnname which matches a value that is stored in variable given in the following code.
When I execute this , I get an error : Error using ==> database.exec Too many input arguments.
q=value;%computed value.
conn1=database('Dbname','','');
fna=exec(conn1,'select * from table1 where ImageName="',q,'"');
fna=fetch(fna); fda=fna.data;
You are passing four input arguments, the last three ones must be concatitated to one sql command.
sqlquery=['select * from table1 where ImageName="',q,'"'];
fna=exec(conn1,sqlquery);
in the matlab manual it says that exec has the following syntax:
curs = exec(conn,sqlquery)
curs = exec(conn,sqlquery,qTimeOut)
You have four parameters in the exec functions, that's what the error means!

SSIS 2008 how to use EXEC

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

Error SQL0104 when creating a function in System i V7R1

I'm creating a SQL function on System i V7R1:
CREATE FUNCTION MYSCHEMA.GROUPDIBAS(v_code VARCHAR(50))
RETURNS VARCHAR(2048)
LANGUAGE SQL
BEGIN
DECLARE str VARCHAR(2048);
SET str = '';
FOR row AS (
SELECT
FIELD2
FROM MYSCHEMA.DIBAS
WHERE FIELD1 = v_code
)
DO
SET str = 'Bubi'; --I removed many statements to make clear the problem doesn't come from them
END FOR;
RETURN str;
END
;
I execute it with "Run SQL script" tool, which is part of the iSeries Navigator V7R1.
It works on another V7R1 server (using iSeries Navigator V5R4), but not in that one where I'm working now. It fails with this message:
SQL State: 42601
Vendor Code: -104
Message: [SQL0104] Token <END-OF-STATEMENT> was not valid. Valid tokens: ;.
Cause . . . . . : A syntax error was detected at token <END-OF-STATEMENT>.
Token <END-OF-STATEMENT> is not a valid token. A partial list of valid tokens is ;.
This list assumes that the statement is correct up to the token.
The error may be earlier in the statement, but the syntax of the statement appears to be valid up to this point.
Recovery . . . : Do one or more of the following and try the request again:
-- Verify the SQL statement in the area of the token <END-OF-STATEMENT>. Correct the statement.
The error could be a missing comma or quotation mark, it could be a misspelled word, or it could be related to the order of clauses.
-- If the error token is <END-OF-STATEMENT>, correct the SQL statement because it does not end with a valid clause.
If I remove the FOR block, it works.
Moreover if I execute the statement with 5250 Emulator, command STRSQL, it works. So it seems like a bug in "Run SQL script" client.
Any hint will be appreciated!
The issue is with the FOR statement. The query analyzer is inconsistent on when the cursor-name CURSOR FOR is optional and when it is required even though the documentation states if it is not specifified a unique cursor name is generated. SQL submitted via the IBM Access Navigator Run Scripts utility require it.
The parenthesis are also incorrect but sometimes they are accepted (STRSQL, Navigator Run SQL Scripts) and sometimes they aren't (DBVisualizer/JDBC).
TIL there must be a different query analyzer running depending on the source of the query.
CREATE FUNCTION MYSCHEMA.GROUPDIBAS(v_code VARCHAR(50))
RETURNS VARCHAR(2048)
LANGUAGE SQL
BEGIN
DECLARE str VARCHAR(2048);
SET str = '';
FOR row AS C1 CURSOR FOR
SELECT
FIELD2
FROM MYSCHEMA.DIBAS
WHERE FIELD1 = v_code
DO
SET str = 'Bubi'; --I removed many statements to make clear the problem doesn't come from them
END FOR;
RETURN str;
END
Given the tests made by #JamesA and me, I fear the problem can be in the Program Temporary Fix (PTF) that this server hasn't and the other ones have. Specifically, running WRKPTFGRP command, I can guess it probably misses this PTF group:
PTF group Level Text
SF99701 5 DB2 FOR IBM I
Unfortunately I can't try installing it now :(.
In the session properties of your IDE change the Statement Separator field value from ; to | then reconnect your session. then use | instead of ;. this way you can run your statement or procedure or function.
usage example,
CREATE FUNCTION MYSCHEMA.GROUPDIBAS(v_code VARCHAR(50))
RETURNS VARCHAR(2048)
LANGUAGE SQL
BEGIN
DECLARE str VARCHAR(2048);
SET str = '';
FOR row AS C1 CURSOR FOR
SELECT
FIELD2
FROM MYSCHEMA.DIBAS
WHERE FIELD1 = v_code
DO
SET str = 'Bubi'; --I removed many statements to make clear the problem doesn't come from them
END FOR;
RETURN str;
END |