可编写存储过程或Delphi程序实现,应该说存储过程更有效率,
1)以下是存储过程脚本:
Create Procedure dbo.M_Query
as
Declare
@TabName varchar(20),
@UnionTab varchar(1000),
@SelectScript VarChar(2000)
Declare Cr_M Cursor for
select Distinct('PODJ20'+SUBSTRING(Po号,2,2)) as TableName from Ck200011
for read only
open Cr_M
Fetch Cr_M into @TabName
while @@Fetch_Status<>-1
begin
if @UnionTab='' or @UnionTab is null
set @UnionTab='Select Po号,单价 from '+@TabName
else
Set @UnionTab=@UnionTab+' Union '+'Select Po号,单价 from '+@TabName
fetch next from Cr_M into @TabName
end
close Cr_M
deallocate Cr_M
set @SelectScript='Select sum(数量*单价) From Ck200011 a,('+@UnionTab+') as b where a.Po号=b.Po号'
exec(@SelectScript)
2)Delphi源码
var
UnionTab:String;
SQLScript:String;
begin
AdoDataSet1.Close;
AdoDataSet1.CommandText:='select Distinct('''+'PODJ20''+'+'SUBSTRING(Po号,2,2)) as TableName from Ck200011';
AdoDataSet1.Open;
with AdoDataSet1 do
While not Eof do
begin
if UnionTab='' then
UnionTab:='Select Po号,单价 from '+FieldByName('TableName').AsString
else
UnionTab:=UnionTab+' Union '+'Select Po号,单价 from '+FieldByName('TableName').AsString;
Next;
end;
AdoDataSet1.Close;
SQLScript:='Select sum(数量*单价) From Ck200011 a,('+UnionTab+') as b where a.Po号=b.Po号 ';
end;