Delphi TFDStoredProc parameter default values missing (MS SQL) - sql-server

I am migrating from ADO to FireDAC. After replacing TADOStoredProc to TFDStoredProc I have the following issue. My _OpenStp procedure opens a stored procedure having default values in its parameter list, and I don't want to pass all those parameters. E.g.
CREATE PROCEDURE [dbo].[usp_SearchDocument]
#User_Id INT
, #Window_Id INT = 10
, #Page INT = 1
...
The core of my procedure:
procedure _OpenStp(
const AConnection: TFDConnection;
var AStp: TFDStoredProc;
const AStpName: string;
const AParamNameA: array of string;
const AParamValueA: array of Variant);
var
i: Integer;
begin
if AStp <> nil then
begin
if AStp.Active then
AStp.Close;
end
else
AStp := TFDStoredProc.Create(nil);
AStp.Connection := AConnection;
AStp.StoredProcName := AStpName;
AStp.Prepare;
for i := Low(AParamNameA) to High(AParamNameA) do
AStp.Params.ParamByName(AParamNameA[i]).Value := AParamValueA[i];
AStp.Open;
end;
The Delphi code of the call:
_OpenStp(SomeConnection, SomeStp, 'usp_SearchDocument',
['User_Id'], [150]);
According to SQL Server Profiler the call was:
exec [dbo].[usp_SearchDocument]
#User_Id=150,
#Window_Id=NULL,
#Page=NULL
TFDStoredProc.Prepare doesn't seem to query the default values of the sp parameters. When I was using the ADO counterpart of my _OpenStp procedure, the TADOStoredProc.Parameters.Refresh method did that job:
procedure _OpenStp(
const AConnection: TADOConnection;
var AStp: TADOStoredProc;
const AStpName: string;
const AParamNameA: array of string;
const AParamValueA: array of Variant);
begin
if AStp <> nil then
begin
if AStp.Active then
AStp.Close;
end
else
AStp := TADOStoredProc.Create(nil);
AStp.Connection := AConnection;
AStp.ProcedureName := AStpName;
AStp.Parameters.Refresh;
for i := 0 to Length(AParamNameA) - 1 do
AStp.Parameters.ParamByName(AParamNameA[i]).Value := AParamValueA[i];
AStp.Open;
end;
SQL Server Profiler:
exec usp_SearchDocument 150,default,default
Unfortunately it isn't an option to rewrite the code to pass all of the parameters, I have to rely on sp parameter default values. Is there a way to modify the FireDAC version of my _OpenStp procedure to achieve this goal?
Edit: I don't even have information about the type of the parameters (see the _OpenStp procedure), I only know their names and the values to be set, so I can't create the TFDParams programmatically.
Edit#2: An EArgumentOutOfRangeException was thrown after deleting the unnecessary parameters:
for i := AStp.ParamCount - 1 downto 0 do
if AStp.Params[i].Name <> '#RETURN_VALUE' then
begin
ExistsInArray := False;
for j := Low(AParamNameA) to High(AParamNameA) do
if Char.ToLower(AStp.Params[i].Name) = Char.ToLower(Format('#%s', [AParamNameA[j]])) then
begin
ExistsInArray := True;
Break;
end;
if not ExistsInArray then
AStp.Params.Delete(i);
end;

Related

Use SQL Server table-valued parameters without creating a type on the SQL Server

I'm trying to pass several values on a single parameter (table-valued parameter) and it works fine following the sample
C:\Users\Public\Documents\Embarcadero\Studio\21.0\Samples\Object Pascal\Database\FireDAC\Samples\DBMS Specific\MSSQL\TVP
SQL:
create type TVPType as table(Code integer, Name varchar(100), RegDate datetime, Notes varchar(max))
go
create table TVPTab(Code integer, Name varchar(100), RegDate datetime, Notes varchar(max))
go
Delphi:
procedure TForm1.btnQryManualSetupClick(Sender: TObject);
var
oDS: TFDMemTable;
i: Integer;
begin
Start;
FDQuery2.SQL.Text := 'insert into TVPTab (Code, Name, RegDate, Notes) ' +
'select Code, Name, RegDate, Notes from :t';
oDS := TFDMemTable.Create(nil);
oDS.FieldDefs.Add('Code', ftInteger);
oDS.FieldDefs.Add('Name', ftString, 100);
oDS.FieldDefs.Add('RegDate', ftTimeStamp);
oDS.FieldDefs.Add('Notes', ftMemo);
FDQuery2.Params[0].DataTypeName := 'TVPType';
FDQuery2.Params[0].AsDataSet := oDS;
(FDQuery2.Params[0].AsDataSet as TFDMemTable).EmptyDataSet;
for i := 1 to C_Recs do
with FDQuery2.Params[0].AsDataSet do begin
Append;
Fields[0].AsInteger := i;
Fields[1].AsString := 'str' + IntToStr(i * 10);
Fields[2].AsDateTime := Now() + i;
Fields[3].AsString := StringOfChar('x', 1000);
Post;
end;
FDConnection1.StartTransaction;
FDQuery2.Execute;
FDConnection1.Commit;
Done('TVP Qry manual setup');
end;
The problem with this code is that it forces me to create a type (in this case the TVPType type) on the server, and I would like to use these table-valued parameters without having to create any object on the server.
Can it be done ?. I have tried defining the parameter as ftDataset but I get an error: The data type READONLY cannot be found.
procedure TForm1.btnQryManualSetupClick(Sender: TObject);
var
oDS: TFDMemTable;
i: Integer;
begin
Start;
FDQuery2.SQL.Text := 'insert into TVPTab (Code, Name, RegDate, Notes) ' +
'select Code, Name, RegDate, Notes from :t';
oDS := TFDMemTable.Create(nil);
oDS.FieldDefs.Add('Code', ftInteger);
oDS.FieldDefs.Add('Name', ftString, 100);
oDS.FieldDefs.Add('RegDate', ftTimeStamp);
oDS.FieldDefs.Add('Notes', ftMemo);
//FDQuery2.Params[0].DataTypeName := 'TVPType';
FDQuery2.Params[0].DataType := ftDataset;
FDQuery2.Params[0].AsDataSet := oDS;
(FDQuery2.Params[0].AsDataSet as TFDMemTable).EmptyDataSet;
for i := 1 to C_Recs do
with FDQuery2.Params[0].AsDataSet do begin
Append;
Fields[0].AsInteger := i;
Fields[1].AsString := 'str' + IntToStr(i * 10);
Fields[2].AsDateTime := Now() + i;
Fields[3].AsString := StringOfChar('x', 1000);
Post;
end;
FDConnection1.StartTransaction;
FDQuery2.Execute;
FDConnection1.Commit;
Done('TVP Qry manual setup');
end;
No. If your multiple values are just a single row you can look into passing them as a comma-separated string and then use the STRING_SPLIT function, or using temp or permanent tables to store multi-row values.

How to get the SQL content of the stored procedure in Delphi code?

I'm debugging Delphi code with Delphi 7 IDE, the code is not mine. My goal is to understand how this code works. This will help me to write my application which will interface with this code.
I never used Delphi in my life. I'm a C, C++, C# programmer.
I'm able to see the output (result) of the stored procedure but I need to see the content of the stored procedure (I mean the SQL statement). I looked in SQL Server side but I didn't find anything.
The stored procedure is called in this function :
function TDBDM.getID( prKeyName : string ) : integer;
begin
try
spGetSN.Parameters.ParamValues['#prKeyname'] := prKeyName;
spGetSN.open;
result := spGetSN.Fields[0].AsInteger;
finally
spGetSN.close;
end;
end;
and the stored procedure 'spGetSN' is declared here :
unit dmDB;
interface
uses
SysUtils, Classes, Forms, ADODB, DB, TypInfo, Dialogs, StdCtrls,
Controls,Registry, Windows;
type
eConnectionType = (ctSN);
TDBDM = class(TDataModule)
ADOConnectionSN: TADOConnection;
spGetSN: TADOStoredProc;
ADOQueryGetPartNoFromRMA: TADOQuery;
ADOQueryGetPartNoFromOrder: TADOQuery;
procedure ADOConnectionSNBeforeConnect(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
function GetConnection( prConnectionType : eConnectionType ) :
TADOConnection;
public
{ Public declarations }
function getID( prKeyName : string ) : integer;
function getSN( prKeyName : string ) : string;
function getCommaValues( prSelect : string; prConnection :
eConnectionType = ctSN ) : string;
property pConnection[prType : eConnectionType] : TADOConnection read
GetConnection; default;
end;
var
DBDM: TDBDM;
implementation
uses dmRegistryClasses;
{$R *.dfm}
The text of the object TADOSTOREDPROC 'spGetSN' as defined in the IDE is :
object spGetSN: TADOStoredProc
Connection = ADOConnectionSN
ProcedureName = 'spGetSN;1'
Parameters = <
item
Name = '#RETURN_VALUE'
DataType = ftInteger
Direction = pdReturnValue
Precision = 10
Value = Null
end
item
Name = '#prKeyname'
Attributes = [paNullable]
DataType = ftWideString
Size = 30
Value = Null
end>
Left = 268
Top = 80
end
How can I print or watch the SQL code of this stored procedure in Delphi debugger? Thanks
The following should give you an idea how to do it:
Add a TAdoQuery called AdoQuerySP to your form and set its connection to whatever AdoConnection component you're using at the moment.
Add a TMemo to the form.
Add a TButton to the form and set its OnClick handler to execute the code below (after changing checklibuse to the name of your SP).
Code:
procedure TForm1.GetSPDefinition;
var
S : String;
begin
S := '';
AdoQuerySP.Sql.Text := 'exec sp_helptext checklibuse'; // sp_helptext
// is a Sql Server system stored proc to retrieve the definition of
// a stored proc. The definition is returned as a series of rows which need to be
// concatenated together as in the `while ...` loop below.
AdoQuerySP.Open;
while not AdoQuerySP.Eof do begin
if S <> '' then
S := #13#10 + S;
S := S + AdoQuerySP.FieldByName('Text').AsString;
AdoQuerySP.Next;
end;
// The retrieved definition is typically preceded by a number of blank lines
// which the call to Trim() remove.
Memo1.Lines.Text := Trim(S);
end;
You could query the sys.sql_modules table e.g.:
function MSSQL_GetModuleText(conn: TADOConnection; const ModuleName: WideString): WideString;
var
SQL: WideString;
rs: Variant;
begin
SQL := Format('SELECT [definition] FROM sys.sql_modules WHERE [object_id]=OBJECT_ID(N''%s'')', [ModuleName]);
rs := conn.Execute(SQL);
Result := VarToWideStr(rs.Fields[0]);
end;
Usage:
S := MSSQL_GetModuleText(ADOConnectionSN, 'dbo.spGetSN');

Import data from Excel into SQL Server

I need to import data from Excel into a SQL Server database. I use ADO to read the excel files.
Sometimes it happens that a row is empty in Excel, which will create an empty row import failure on the SQL Server side.
Any good idea to remove these empty rows or detect during import?
I'm looking for a rather effective code style solution, i show my current solution with the field loop here
function EmptyRow(aQuery: TADOQuery): Boolean;
var
i: Integer;
fname: string;
temp_line: string;
begin
temp_line := '';
for i := 0 to aQuery.Fields.Count - 1 do
begin
fname := aQuery.Fields[i].FieldName;
temp_line := temp_line + aQuery.FieldByName(fname).asString;
end;
if (temp_line <> '') then
result := false
else
result := true;
end;
You could exit the first thime you find a non empty string
function EmptyRow(aQuery: TADOQuery): Boolean;
var
Field: TField;
begin
for Field in aQuery.Fields do
if Field.AsString <> '' then
exit(false);
exit(True);
end;
And if you have an older Delphi you could implement it like tihs:
function EmptyRow(aQuery: TADOQuery): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to aQuery.Fields.Count - 1 do
if aQuery.Fields[I].AsString <> '' then
exit;
Result := True;
end;

What is the proper way to dynamically create and call a stored procedure in Delphi using FireDac?

I am relatively new to FireDAC. I want to be able to call a stored procedure "on the fly", dynamically. So far I have the following:
function TForm21.ExecuteStoredProc(aSPName: string; aParams: TADParams): Boolean;
var
LSP: TADStoredProc;
i: Integer;
begin
LSP := TADStoredProc.Create(nil);
try
LSP.Connection := ADConnection1;
LSP.StoredProcName := aSPName;
LSP.Prepare;
for i := 0 to aParams.Count - 1 do
begin
LSP.Params[i].Value := aParams[i].Value;
end;
LSP.ExecProc;
finally
LSP.Free;
end;
Result := True;
end;
I call it with
procedure TForm21.Button1Click(Sender: TObject);
var
LParams: TADParams;
begin
LParams := TADParams.Create;
LParams.Add.Value := 612;
LParams.Add.Value := '2008';
ExecuteStoredProc('HDMTEST.dbo.spARCHIVE_HISTORY_DATA', LParams);
end;
However, the stored procedure fails to execute. That is, the code runs fine, no error message is shown, but the stored procedure doesn't run.
Further info -- it runs fine if I drop a component and set up the params in code.
Anyone have any idea what I am missing?
Seeing as this q has been left unanswered for a while, I thought I'd try to get the code working without using the clues from the comments and found it not quite as easy as I'd imagined.
I immediately got stuck with the SP params. I found this
http://docwiki.embarcadero.com/RADStudio/XE5/en/TFDQuery,_TFDStoredProc_and_TFDUpdateSQL_Questions
which says
"If you have difficulties with manual definition of parameters,
populate the Params collection automatically and check how the
parameters are defined. Then compare that to your code. "
but I couldn't find a way of "automatically" populating the Params. I asked on the EMBA
FireDac newsgroup and the FD author, Dimitry Arefiev, kindly explained that
you can do that by checking that the FetchOptions include fiMeta, and then clearing and setting the FDStoredProc's StoredProcName.
Using a StoredProc in the pubs demo database on my SqlServer defined as follows:
create procedure test(#ANumber int, #AName varchar(20))
as
begin
select
#ANumber * 2 as "Number",
#AName + #AName as "Name"
end
I changed a couple of sections of the OP's code like this
[...]
LSP.Params.Clear;
LSP.StoredProcName := '';
LSP.FetchOptions.Items := LSP.FetchOptions.Items + [fiMeta];
LSP.StoredProcName := aSPName;
LSP.Prepare;
Assert(LSP.ParamCount > 0);
for i := 0 to aParams.Count - 1 do
begin
LSP.Params.ParamByName(aParams[i].Name).Value := aParams[i].Value;
end;
[...]
procedure TForm21.Button1Click(Sender: TObject);
var
LParams: TFDParams;
Param : TFDParam;
begin
LParams := TFDParams.Create;
Param := LParams.Add;
Param.Name := '#ANumber';
Param.Value := 612;
Param := LParams.Add;
Param.Name := '#AName';
Param.Value := '2008';
ExecuteStoredProc('test', LParams);
end;
and it worked fine.
The OP mentions in the q he'd first had the problem that the SP failed to execute
but that he'd found that it worked if he "[dropped] a component and set up the params in code" so I thought I'd include here a console application where of course necessarily everything is done in code. This wasn't difficult, but the time it took me to get the Uses clause right is my main reason for posting this as an answer, for future reference. W/o the correct uses, you get errors complaining about various class factories being missing.
Console app (created and tested in XE6):
program ConsoleStoredProcProject3;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, FireDac.DApt, FireDAC.Stan.Def, FireDAC.Stan.ASync,
FireDAC.Stan.Param, FireDAC.Stan.Option, FireDAC.Comp.Client,
FireDAC.Phys.MSSQL, VCL.ClipBrd;
procedure TestSP;
var
Connection : TFDConnection;
StoredProc : TFDStoredProc;
Param : TFDParam;
begin
Connection := TFDConnection.Create(Nil);
Connection.DriverName := 'MSSQL';
Connection.Params.Values['Server'] := // your server name'';
Connection.Params.Values['Database'] := 'pubs';
Connection.Params.Values['user_name'] := 'user'; // adjust to suit
Connection.Params.Values['password'] := 'password'; // ditto
Connection.LoginPrompt := False;
Connection.Connected := True;
StoredProc := TFDStoredProc.Create(Nil);
StoredProc.Connection := Connection;
StoredProc.FetchOptions.Items := StoredProc.FetchOptions.Items + [fiMeta];
StoredProc.StoredProcName := 'test';
StoredProc.Prepare;
Param := StoredProc.Params.ParamByName('#ANumber');
Param.Value := 333;
Param := StoredProc.Params.ParamByName('#AName');
Param.Value := 'A';
StoredProc.Active := True;
WriteLn(StoredProc.FieldByName('Number').AsInteger);
WriteLn(StoredProc.FieldByName('Name').AsString);
ReadLn;
end;
begin
try
TestSP;
except
on E: Exception do
Clipboard.AsText := E.Message;
end;
end.

Calling SQL Server stored procs from Delphi with arguments?

I'm trying to call SP_SPACEUSED from Delphi 2010 using ADO. I can call it without arguments by using TSQLStoredProc, and setting the StoredProcName. This gives me the database size. I now need a specific table size, and SP_SPACEUSED takes a single arugument, #objname. How do I pass this as an argument. I have tried passing this as a parameter, but this doesn't work. Is it a parameter? Can I do this from Delphi?
Quick and dirty example (in D6 but it should work without any change in 2010):
var
I: Integer;
adStoredProc : TADOStoredProc;
begin
adStoredProc := TADOStoredProc.Create(nil);
try
adStoredProc.Connection := ADOConnection1;
adStoredProc.ProcedureName := 'SP_SPACEUSED';
adStoredProc.Parameters.Refresh;
for I := 0 to adStoredProc.Parameters.Count - 1 do // Iterate
begin
if Sametext(adStoredProc.Parameters[i].Name,'#objname') then
adStoredProc.Parameters[i].Value := 't_config';
end; // for
adStoredProc.Open;
for I := 0 to adStoredProc.FieldCount - 1 do // Iterate
begin
memo1.Lines.Append(format('%s : %s', [adStoredProc.Fields[i].Fieldname, adStoredProc.Fields[i].AsString]));
end; // for
finally
FreeAndNil(adStoredProc);
end;
end;

Resources