2014-06-12 206 views
4

我需要将参数作为表值传递给SQL Server中的存储过程。如何在Delphi中处理这个问题?Delphi - 将表值参数传递给SQL Server存储过程

+1

[Devart SDAC](http://forums.devart.com/viewtopic.php?f=6&t=24223)支持TVP,但是ADO(Delphi TADOxxx组件)[不支持TVP](http:// stackoverflow的.com /问题/ 1883852 /经典ADO和 - 表值参数-在存储过程)。 – whosrdaddy

+0

感谢您的回复@whosrdaddy – user3733328

回答

5

据我所知,在那里没有简单的方法来传递表参数,使用Delphi的组件。 解决方法是使用可用于填充类型化表变量的临时表。

假设你的定义是这样的:

CREATE TYPE MyTableType AS TABLE 
(ID int 
, Text varchar(100)) 
GO 

CREATE PROCEDURE P_Table 
    @Tab MyTableType READONLY 
AS 
BEGIN 
    SET NOCOUNT ON; 
    Select * from @Tab -- dummy operation just return the dataset 
END 
GO 

你可以这样调用的程序:

var 
    i: Integer; 
begin 
    // we create a temporary table since a table variable can obly be used for a single call 
    DummyDataset.Connection.Execute('Create Table #mytemp(ID int,Text varchar(100))'); 
    DummyDataset.CommandText := 'Select * from #mytemp'; 
    DummyDataset.Open; 
    for i := 0 to 10 do 
    begin 
    DummyDataset.Append; 
    DummyDataset.Fields[0].Value := i; 
    DummyDataset.Fields[1].Value := Format('A Text %d', [i]); 
    DummyDataset.Post; 
    end; 
    MyDataset.CommandText := 'Declare @mytemp as MyTableType ' 
         + 'Insert into @mytemp select * from #mytemp ' // copy data to typed table variable 
         + 'EXEC P_Table @Tab = @mytemp'; 
    MyDataset.Open; 
    DummyDataset.Connection.Execute('Drop Table #mytemp'); 
end 
+0

嗨Bummi,感谢您的快速回答。是否有可能使用clientdataset将表值参数传递给delphi。 – user3733328

0

http://msftdpprodsamples.codeplex.com/wikipage?title=SS2008%21Readme_Table-Valued%20Parameters样本下载是用C++编写,但可以很容易地转换为德尔福。

一旦转换的代码德尔福,你可以使用类似下面让结果集通过老好人ADO访问:

SourcesRecordset := CreateADOObject(CLASS_Recordset) as _Recordset; 
RSCon := SourcesRecordset as ADORecordsetConstruction; 
RSCon.Rowset := rowset; 

LDataSet := TADODataSet.Create(nil); 
try 
    // Only doing the first result set 
    LDataSet.Recordset := SourcesRecordset; 
    while not LDataSet.Eof do 
    begin 
    //... something 
    LDataSet.Next; 
    end; 
finally 
    LDataSet.Free; 
end; 

注意CreateADOObjectData.Win.ADODB.pas一个私人的功能,但它是相当不重要的。

+0

有趣的答案。它可能会从你的答案中的(代码)例子中受益,例如,如何将它应用于已经使用TAdoxxx组件的Delphi项目中。 – MartynA

+0

好点。现在工作(因为我也需要它)... –

+0

好,我会投它。我认为它只需要一个提纲,fwiw。 – MartynA

相关问题