使用 SAPFunctions.CreateStructure()
方法获取 DDIC (SAP data dictionary) 的字段信息。
本篇主要演示 C# 调用的语法,VBA 版有相关知识点介绍,请参考之前的博文。
首先定义一个存储 DDIC 信息的结构:
public struct DDICInfo
{
public String ColumnName;
public String ColumnType;
public int ColumnLength;
}
另外,CreateStructure()
返回的是 SAPFunctionsOCX.Structure
类型,因为 Structure
是一个 COM 类型结构,所以转换成List<DDICInfo>
方便后续处理。
private List<DDICInfo> Convert(SAPFunctionsOCX.Structure sapFunStruct)
{
var ddicFields = new List<DDICInfo>();
var ddicItem = new DDICInfo();
for (int i = 1; i <= sapFunStruct.ColumnCount; i++) {
ddicItem.ColumnName = sapFunStruct.get_ColumnName((short) i);
ddicItem.ColumnType = sapFunStruct.get_ColumnSAPType(i).ToString();
ddicItem.ColumnLength = sapFunStruct.get_ColumnLength(i);
ddicFields.Add(ddicItem);
}
return ddicFields;
}
完整代码:
using System;
using System.Collections.Generic;
using SAPLogonCtrl;
using SAPFunctionsOCX;
using ConnectionProvider;
namespace SAPRfcCall
{
public struct DDICInfo
{
public String ColumnName;
public String ColumnType;
public int ColumnLength;
}
public class DDICStructure
{
private Connection connection;
public List<DDICInfo> GetDDICDemo()
{
var ddicFields = new List<DDICInfo>();
bool isSuccessful = SAPConnection.SilentLogon(
"192.168.65.100", "D01", 00, "001", "STONE", "sappwd", "ZH");
if (isSuccessful) {
connection = SAPConnection.Connection;
ddicFields = GetFieldsFrom("SKB1");
SAPConnection.Logoff();
}
return ddicFields;
}
// get table structure
public List<DDICInfo> GetFieldsFrom(String tableName)
{
var ddicFields = new List<DDICInfo>();
if (connection == null
|| connection.IsConnected != CRfcConnectionStatus.tloRfcConnected) {
return null;
}
SAPFunctions functions = new SAPFunctions();
functions.Connection = connection;
SAPFunctionsOCX.Structure ddic = functions.CreateStructure(tableName);
ddicFields = this.Convert(ddic);
return ddicFields;
}
private List<DDICInfo> Convert(SAPFunctionsOCX.Structure sapFunStruct)
{
var ddicFields = new List<DDICInfo>();
var ddicItem = new DDICInfo();
for (int i = 1; i <= sapFunStruct.ColumnCount; i++) {
ddicItem.ColumnName = sapFunStruct.get_ColumnName((short)i);
ddicItem.ColumnType = sapFunStruct.get_ColumnSAPType(i).ToString();
ddicItem.ColumnLength = sapFunStruct.get_ColumnLength(i);
ddicFields.Add(ddicItem);
}
return ddicFields;
}
}
}
单元测试:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SAPRfcCall;
using System.Collections.Generic;
namespace UnitTestProject
{
[TestClass]
public class TestGetDDIC
{
[TestMethod]
public void Test_GetDDIC()
{
DDICStructure ddic = new DDICStructure();
List<DDICInfo> fields = ddic.GetDDICDemo();
foreach (DDICInfo item in fields) {
Console.WriteLine(String.Format("{0}\t{1}\t{2}",
item.ColumnName ,
item.ColumnType,
item.ColumnLength));
}
}
}
}