Pass NULL parameter to TFDConnection.ExecSQLScalar - delphi

Is there a possibility to pass NULL value to some parameter of this FireDAC query?:
conn: TFDConnection;
fPar1, fPar2, fPar3: OleVariant;
cnt := conn.ExecSQLScalar(
'SELECT COUNT(*) FROM my_table WHERE par1=:p1 AND par2=:p2 AND par3=:p3',
[fPar1, fPar2, fPar3]
);
Is it possible without intermediate TFDQuery using TFDConnection object only?

Yes, you can do this, despite the fact that the parameters TFDConnection uses
for ExecSQLScalar are not directly accessible from your calling code, but it may not produce the result you are expecting unless you modify your SQL - see below.
Presumably, you have had an error message like "[FireDAC] parameter type [fPar2 ] is unknown ..." if you set fPar2 to Null beforehand.
You can avoid that by using the override of ExecSQLScalar that allows you to specify
the field types of the parameters in an open array following the parameter
which lists the variants, as in e.g.
cnt := conn.ExecSQLScalar(
'SELECT COUNT(*) FROM my_table WHERE par1=:p1 AND par2=:p2 AND par3=:p3',
[fPar1, fPar2, fPar3],
[ftString, ftString, ftString] // or whatever
);
See
function TFDCustomConnection.ExecSQLScalar(const ASQL: String;
const AParams: array of Variant; const ATypes: array of TFieldType): Variant;
in FireDAC.Comp.Client.Pas
BUT, on my data here, this does NOT produce the correct count value (using Seattle and SS2014) presumably because of Uwe Raabe's good point about par1 = Null versus par1 is Null. To get the correct answer, I had to modify the SQL as per Keith Miller's comment to include set ansi_nulls off before SELECT ...

Related

Assigning default value to snowflake stored procedure arguments

Is it possible to have default values in arguments of Stored procedures of Snowflake. For the below example, I am getting error. Please help
syntax error line 1 at position 53 unexpected ''test''.
create or replace procedure test(arg1 string default 'test')
returns string not null
language sql
as
$$
begin
return arg1;
end;
$$
;
Snowflake's procedures applies polymorphism instead of using default value. This solution is when you do not want to call sp like func1(Null)
For example (sql scripting):
create or replace procedure func1(arg1 varchar, arg2 varchar)
...
create or replace procedure func1(arg1 varchar)
...
call func1(arg1 , 'some-default-value')
...
One option could be providing NULL as value and handle it at the begining of the stored procedure with COALSESCE:
create or replace procedure test(arg1 string)
returns string not null
language sql
as
$$
begin
arg1 := COALESCE(arg1, 'test');
return arg1;
end;
$$;
CALL test(NULL);
-- test
Setting a default value/values as arguments directly in Stored procedures is not available in Snowflake currently
The below link can be referred for the allowed syntax in Stored Procedures
https://docs.snowflake.com/en/sql-reference/sql/create-procedure.html#syntax

How to define an Array of values (or a Column) into a Procedure Argument?

I am working on a Netezza SP and is stuck with a problem.
I have a SP, defined as say:
CREATE OR REPLACE PROCEDURE MY_PROC(VARCHAR(ANY)) RETURNS INTEGER LANGUAGE NZPLSQL
AS
BEGIN_PROC
DECLARE
v_temp ALIAS FOR $1;
/* Other decalarations */
result_ts INTEGER;
BEGIN
result_ts := 0;
/* Procedure Body */
RETURN result_ts;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'Exception Raised: %', SQLERRM;
END;
END_PROC;
If I am running this SP with one value, such as:
SELECT MY_PROC('TEST_INPUT');
But if I am trying to run it with a column value, such as:
SELECT MY_PROC(TEST_COLUMN) FROM TEST_TABLE;
Its giving me error as:
ERROR: Can't use a stored procedure in this context
I know that in the second scenario I am passing an Array (i guess) but this is not what the Procedure has expected.
Now I am trying to have a procedure that can accept these kind of values but could not succeeded so far, LOOPing and all I have taken care but only problem is the Argument which I don't know how to pass.
Any help would be appreciated, let me know if I need to provide any extra info on this.
Asif
Stored procedures in Netezza, as of v7.2, can only be called in the following ways, as documented here.
CALL sproc_name(...);
EXEC sproc_name(...);
SELECT sproc_name(...);
Note that the SELECT form does not allow a FROM clause.
If you want the stored procedure to act on a particular column from a particular table that changes from invocation to invocation, you could pass the names of those as arguments to the stored procedure and have the entirety of the SQL logic encoded within. You could even pass arbitrary code into the stored procedure to build a query internally.
The way you are trying to call it now is more like calling a user defined function, and that simply won't work with stored procedures here.

How big is an nvarchar(max) as far as ADO is concerned?

i am trying to use a parameterized query against ADO:
INSERT INTO Foo (Name, Value) VALUES(#name, #value)
In SQL Server the Name column is a varchar type. The Value column is an nvarchar(max).
What size do i pass when creating a parameter when i don't know, or want to specify, the size?
procedure SaveTheThing(Connection: TADOConnection);
var
sql: WideString;
cmd: _Command;
begin
sql := 'INSERT INTO Foo (Name, Value) VALUES(#name, #value)';
cmd := CoCommand.Create;
cmd.Set_ActiveConnection(Connection.ConnectionObject);
cmd.Set_CommandType(adCmdText);
cmd.Set_CommandText(sql);
//and now add the parameters
cmd.Parameters.Append(
cmd.CreateParameter('#name', adVarChar, adParamInput, -1, filename)
);
cmd.Parameters.Append(
cmd.CreateParameter('#value', adVarWChar, adParamInput, -1, GetXmlToWideString)
);
cmd.Execute({out}recordsAffected, EmptyParam, adCmdSomeThatDoesntCauseAnExcetpion or adExecuteNoRecords);
end;
The simple alternative was going to be:
sql := 'INSERT INTO Foo (Name, Value)'#13#10+
'VALUES (+QuotedStr(filename)+', '+QuotedStrW(GetXmlToWideString)+')';
and be done already. But i thought i'd burn a few days trying to make parameterized queries a viable solution, and avoid having to write a QuotedStrW.
You can use the -1 value in the size of a ADO parameter without problems.
Try this sample code , which insert a 2MB string in the Value column
var
sql: WideString;
cmd: _Command;
recordsAffected : OleVariant;
begin
sql := 'INSERT INTO Foo (Name, Value) VALUES(?, ?)';
cmd := CoCommand.Create;
cmd.Set_ActiveConnection(Connection.ConnectionObject);
cmd.Set_CommandType(adCmdText);
cmd.Set_CommandText(sql);
//and now add the parameters
cmd.Parameters.Append(cmd.CreateParameter('#name', adVarChar, adParamInput, -1, 'AfileName'));
cmd.Parameters.Append(cmd.CreateParameter('#value', adVarWChar, adParamInput, -1, StringOfChar('#', 2*1024*1024)));
cmd.Execute({out}recordsAffected, EmptyParam, adExecuteNoRecords);
end;
You can use my answer on your other post:
"Must declare the variable #myvariable" error with ADO parameterized query
to use parameters and parameter by name. Try to avoid using _Command, but use TADOCommand because it is more friendly (and simpler to code too). You can assign parameter to a value by using:
Parameters.ParamByName('xxxx').value := someValue.
Of course someValue data type must correspond to your SQL server column data type definition.

Firebird TIBQuery insert with returning ... INTO

I have a firebird 2.x database with Generator and a trigger to generate the key field.
I need to get the returned value from below query.
INSERT INTO XXXX (vdate,description) values ('"+ VDate +"','"+ Description +"') returning vno INTO :ParamVoucherNo
I tried several versions of below code but it dont wrok and I get
Dynamic sql error sql error code = -104
Is it really possible to get the return value in delphi using TIBQuery ?
Query1->SQL->Clear();
Query1->SQL->Add("INSERT INTO XXXX (vodate,description) values ('"+ VDate +"','"+ Description +"') returning vno INTO :ParamVoucherNo");
Query1->Params->ParamByName("ParamVoucherno")->ParamType = ptResult;
Query1->Params->ParamByName("ParamVoucherno")->DataType = ftInteger;
Query1->Params->ParamByName("ParamVoucherno")->Value = "";
Query1->Prepare();
Query1->ExecSQL();
Any suggestions?
From Firebird README.returning:
The INTO part (i.e. the variable list) is allowed in PSQL only (to
assign local variables) and rejected in DSQL.
As IBX uses DSQL, you should exclude INTO part from your query.
INSERT ... RETURNING for DSQL looks the same as a call of a stored procedure, which returns result set. So, you have to use Open instead of ExecSQL.
Your mixing of dynamic SQL with parameters is just confusing.
Do this instead:
Query1->SQL->Clear();
Query1->SQL->Add("INSERT INTO table1 (vodate,description) VALUES"+
"(:VoDate,:Description) RETURNING vno INTO :VoucherNo ");
Query1->Params->ParamByName("VoDate")->Value = VDate;
Query1->Params->ParamByName("description")->Value = Description;
Query1->Prepare();
Query1->ExecSQL();
VoucherNo = Query1->Params->ParamByName("VoucherNo")->AsInteger;
Using Delphi 6 I have the ID returning successfully using an EXECUTE BLOCK statement:
EXECUTE BLOCK
RETURNS ( DeptKey INT )
AS
BEGIN
INSERT INTO DEPARTMENT
( COMPANY_KEY, DEPARTMENT_NAME )
VALUES ( 1, 'TEST1' ) RETURNING DEPARTMENT_KEY INTO :DeptKey;
SUSPEND;
END;
From Delphi you can do the folliowing:
FQuery.SQL.Text := '<Execute Block Statement>';
FQuery.Open();
ANewKey := FQuery.Fields[0].AsInteger;
IBX is not Firebird ready
you can take a look at FIBPLUS who support Firebird features
FIBPlus also supports FB2.0 insert ... into ... returning. Now you
should not bother about getting generator values from the client but
leave them in the trigger. You can also use RDB$DB_KEY. New possible
variants of work with insert returning and RDB$DB_KEY are shown in the
example “FB2InsertReturning”.
Why not get the next value for VoucherNo first, followed by
"INSERT INTO table1 (vno, vodate,description) VALUES (:VoucherNo,:VoDate,:Description)");
?
Your trigger can then either be dispensed with (which is nice), or modified to detect null (or <= zero can be useful too) and only then populate the vno field.
create trigger bi_mytable
active before insert position 1
on mytable
as
begin
if (new.vno is null)
then new.vno = next value for gen_VoucherNos;
end
Client-side you can :
select gen_id(gen_VoucherNos, 1) from rdb$database;
By modifying the trigger in this manner you save yourself a headache later on if/when you want to insert blocks of records
I wonder if that INSERT can be wrapped into EXECUTE BLOCK command.
Would IBX manage EXECUTE BLOCK then?
http://www.firebirdsql.org/refdocs/langrefupd20-execblock.html
http://firebirdsql.su/doku.php?id=execute_block
Hope to try it in both IBX and Unified Interbase in XE2
PS: Even if it does not, I found the library, that tells to work on top of IBX of Delphi XE2 (both x86 and x64) and to add EXECUTE BLOCK support: http://www.loginovprojects.ru/index.php?page=ibxfbutils#eb.
As I know there should be some changes to IBX made. Internally INSERT ... RETURNING should be treated the same way as a selectable procedure with returning parameters.
i know this question was answered a long time ago, but i must write this as clear as possible, for those who need this as i was.
i too, needed the "INSERT..RETURNING" thing.
the Delphi drove me crazy for a long time, until i changed my Data access components.
i even moved from Delphi XE2, to XE5 only because of that...
conclusion : IBX does NOT support RETURNING!
FireDAC is PERFECT for what i need with Firebird.
just move to FireDAC and you'll be able to do everything you need, and with high performance.
If you have a table with this 2 Fields: GRP_NO and GROUPNAME and you want to get the new GRP_NO you have to use RET_ as prefix, see example:
procedure TFormDatenbank.Button1Click(Sender: TObject);
var
q: Uni.TUniQuery;
ID: Integer;
GroupName: String;
begin
GroupName := 'MyGroupName';
q := TUniQuery.Create(nil);
try
q.Connection := Datenmodul.UniConnection;
q.ParamCheck := true; // the default value of ParamCheck is true.
q.SQL.Clear;
q.SQL.Add('SELECT GRP_NO, GROUPNAME FROM GROUPDATA WHERE GROUPNAME = :GROUPNAME');
q.ParamByName('GROUPNAME').AsString := GroupName;
q.Open;
if q.RecordCount > 0 then
ID := q.FieldByName('GRP_NO').AsInteger
else
begin
// there exist no group with this name, so insert this new name
q.SQL.Clear;
q.SQL.Add('INSERT INTO GROUPDATA');
q.SQL.Add('(GROUPNAME)');
q.SQL.Add('VALUES');
q.SQL.Add('(:GROUPNAME)');
q.SQL.Add('RETURNING GRP_NO;');
q.ParamByName('GROUPNAME').AsString := GroupName;
q.Execute;
ID := q.ParamByName('RET_GRP_NO').AsInteger;
end;
finally
q.Free;
end;
end;
From the IBx2 sources, you can do it like this:
//Uses IBSql;
//var Cur: IResults;
IBSQL1.SQL.Text := 'delete from tbl_document where id = 120 returning id;';
IBSQL1.Prepare;
if IBSQL1.Prepared then
begin
Cur := IBSQL1.Statement.Execute(IBTransaction1.TransactionIntf);
WriteLn(Cur.Data[cou].AsString);
Cur.GetTransaction.Commit(True);
end;
IResults interface Code:
IResults = interface
function getCount: integer;
function GetTransaction: ITransaction;
function ByName(Idx: String): ISQLData;
function getSQLData(index: integer): ISQLData;
procedure GetData(index: integer; var IsNull:boolean; var len: short; var data: PChar);
procedure SetRetainInterfaces(aValue: boolean);
property Data[index: integer]: ISQLData read getSQLData; default;
property Count: integer read getCount;
end;
Test enviroment:
Arch Linux X86
Firebird 3
Lazarus 1.9
FPC 3.0.4
Quick note: This works on new Firebird API in the IBX, But I didn't test it in Legacy Firebird API with the IBX.

EXECUTE IMMEDIATE with USING clause giving errors

All,
I am very new to stored procedures in general but I am struggling especially with those in Oracle. I have created a very simple example of what I am trying to accomplish and I am still getting the same error with this simplified version.
The example stored procedure is as follows:
CREATE OR REPLACE PROCEDURE ashish_test
AUTHID CURRENT_USER IS
BEGIN
DECLARE
v_tab VARCHAR2(50);
v_strSQL VARCHAR2(50);
BEGIN
v_strSQL := 'SELECT * FROM :1';
v_tab := 'ex.emp';
EXECUTE IMMEDIATE v_strSQL USING v_tab;
END;
END;
When I call the above stored procedure using CALL ashish_test(), I get :
Error Message http://web1.twitpic.com/img/12831839-06a3ea536df5d5a0a839eb83d9e59d25.4a3936b8-scaled.jpg
Based on this article (Look for Example 7-1), USING keyword should replace the numbered placeholder (:1) within v_strSQL with the value stored in v_tab. However, I keep getting invalid table error. I am guessing it's because EXECUTE IMMEDIATE is unable to replace the placeholder with the value for some reason but I am not sure why that is. Does anyone know if I am doing something stupid here?
I am running this on Oracle 10g database & using PL/SQL Developer.
The USING clause is only for bind variables (i.e. where you would use column names in a select statement), not table names. Typical usage would look like this:
Select col1 from table1 where col2 = :a
If you want to use variable table names use something like this:
v_tab := 'ex.emp';
v_strSQL := 'SELECT * FROM ' || v_tab;
EXECUTE IMMEDIATE v_strSQL;

Resources