Funkcje zdefiniowane przez użytkownika i procedur przechowywanych
With ADOMD.NET server objects, you can create user defined function (UDF) or stored procedures for Microsoft SQL Server Usługi Analysis Services that interact with metadata and data from the server.Te metody w trakcie są wywoływane za pośrednictwem wyrażeń wielowymiarowych (MDX) lub danych górnictwa rozszerzenia (DMX) instrukcji, która zapewnia dodatkowe funkcje bez opóźnienia związane z siecią łączności.
Przykłady UDF
UDF jest metoda, która może zostać wywołany w kontekście instrukcja MDX lub DMX, można wykonać dowolną liczbą parametrów i może zwracać dowolny typ danych.
UDF utworzone za pomocą języka MDX przypomina utworzonej dla DMX.Podstawową różnicą jest, że niektóre właściwości Context obiektów, takich jak CurrentCube i CurrentMiningModel Właściwości, są dostępne tylko dla jednego języka wykonywanie skryptów lub innych.
Następujące przykłady przedstawiają metody korzystania z formatu UDF zwraca opis węzła, filtr krotek i zastosować filtr do spójna kolekcja.
Zwracanie opis węzła
Poniższy przykład tworzy UDF, która zwraca opis węzła dla określonego węzła.UDF używany jest bieżący kontekst, w którym on uruchamiany i używa DMX Z klauzula, aby pobrać bieżący węzeł model wyszukiwania.
public string GetNodeDescription(string nodeUniqueName)
{
return Context.CurrentMiningModel.GetNodeFromUniqueName(nodeUniqueName).Description;
}
Po wdrożeniu w poprzednim przykładzie UDF może być wywołana przez wyrażenie DMX następujące pobiera najbardziej prawdopodobne przewidywanie węzła.Opis zawiera informacje opisujące warunków, które tworzą węzła przewidywanie.
select Cluster(), SampleAssembly.GetNodeDescription( PredictNodeId(Cluster()) ) FROM [Customer Clusters]
Zwracanie krotek
Poniższy przykład pobiera zestaw i zwrotu liczba i losowo pobiera krotek z zestawu zwrócenie podzbiór końcowego:
public Set RandomSample(Set set, int returnCount)
{
//Return the original set if there are fewer tuples
//in the set than the number requested.
if (set.Tuples.Count <= returnCount)
return set;
System.Random r = new System.Random();
SetBuilder returnSet = new SetBuilder();
//Retrieve random tuples until the return set is filled.
int i = set.Tuples.Count;
foreach (Tuple t in set.Tuples)
{
if (r.Next(i) < returnCount)
{
returnCount--;
returnSet.Add(t);
}
i--;
//Stop the loop if we have enough tuples.
if (returnCount == 0)
break;
}
return returnSet.ToSet();
}
Poprzedni przykład nazywa się w następującym przykładzie MDX.W tym przykładzie MDX pięciu losowe województw są pobierane z Adventure Works bazy danych.
SELECT SampleAssembly.RandomSample([Geography].[State-Province].Members, 5) on ROWS,
[Date].[Calendar].[Calendar Year] on COLUMNS
FROM [Adventure Works]
WHERE [Measures].[Reseller Freight Cost]
Zastosowanie filtru do krotki
W poniższym przykładzie UDF zdefiniowano zestaw przyjmuje i stosuje filtr do każdej spójna kolekcja z zestawu przy użyciu obiektu wyrażenia.Wszelkie krotek, które są zgodne z filtrem zostaną dodane do zestaw, który jest zwracany.
public static Set FilterSet(Set set, String filterExpression)
{
Expression expr = new Expression(filterExpression);
SetBuilder resultSetBuilder = new SetBuilder();
foreach (Tuple tuple in set)
{
if ((bool)(expr.Calculate(tuple)))
{
resultSetBuilder.Add(tuple);
}
}
return resultSetBuilder.ToSet();
}
Poprzedni przykład nazywa się w następującym przykładzie MDX, który filtruje zestaw do miasta z nazwami, począwszy od "A".
Select Measures.Members on Rows,
SampleAssembly.FilterSet([Customer].[Customer Geography].[City], "[Customer].[Customer Geography].[City].CurrentMember.Name < 'B'") on Columns
From [Adventure Works]
Przykład procedury przechowywanej
W poniższym przykładzie procedura składowana na podstawie MDX używa AMO do tworzenia partycji, jeśli to konieczne, sprzedaży przez Internet.
public static void CreateInternetSalesMeasureGroupPartitions()
{
//Check the current state of the data warehouse and
//create partitions with AMO if necessary
#region Retrieve order date of last sales transaction
// Open a connection to the data warehouse
// TODO: Change the first string parameter to reflect the right server\instance.
SqlConnection conn = new SqlConnection(string.Format("data source={0};initial catalog={1};Integrated Security=SSPI", "server\\instance", Context.CurrentDatabaseName));
conn.Open();
// Create a command
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
// Get the order date key of the last internet sale
int lastInternetSaleDateKey = 0;
cmd.CommandText = "select max(OrderDateKey) from FactInternetSales";
lastInternetSaleDateKey = (int)cmd.ExecuteScalar();
// Get the order date key of the last reseller sale
int lastResellerSaleDateKey = 0;
cmd.CommandText = "select max(OrderDateKey) from FactResellerSales";
lastResellerSaleDateKey = (int)cmd.ExecuteScalar();
#endregion
#region Create partitions
// Connect to the calling session
Server svr = new Server();
svr.Connect("*");
// Get the Adventure Works cube
Database db = svr.Databases.GetByName(Context.CurrentDatabaseName);
Cube cube = db.Cubes[0];
MeasureGroup mg;
int maxOrderDateKey;
mg = cube.MeasureGroups.GetByName("Internet Sales");
maxOrderDateKey = 0;
foreach (Partition part in mg.Partitions)
{
maxOrderDateKey = Math.Max(maxOrderDateKey, Convert.ToInt32(
part.Annotations.Find("LastOrderDateKey").Value.Value,
System.Globalization.CultureInfo.InvariantCulture));
}
if (maxOrderDateKey < lastInternetSaleDateKey)
{
Partition part = mg.Partitions.Add("Internet_Sales_"
+ lastInternetSaleDateKey);
part.StorageMode = StorageMode.Molap;
part.Source = new QueryBinding(db.DataSources[0].ID,
"SELECT * FROM [dbo].[FactInternetSales] WHERE OrderDateKey > '"
+ maxOrderDateKey + "' and OrderDateKey <= '" + lastInternetSaleDateKey + "'");
part.Annotations.Add("LastOrderDateKey", Convert.ToString(lastInternetSaleDateKey,
System.Globalization.CultureInfo.InvariantCulture));
part.Update();
part.Process();
}
svr.Disconnect();
#endregion
}