Wednesday, July 29, 2009

How to get data from Firebird database using MS SQL Server stored procedure

In solving one of the tasks (рассчет автокредита) I needed an opportunity to perform stored procedure of SQL Server 2005, to receive data from the FireBird database.

Typically stored procedure in T-SQL can not do this, so I wrote a stored procedure in C#, which receives the necessary data to the DataTable(s), from where then method SqlContext.Pipe.SendResultsRow, passing a string SQL Server.
Here is the example:




public class SQLFIREBIRDCLR
{

[SqlProcedure()]
public static void ProcedureToFirebird(SqlString sServerName, SqlString sDatabaseName)
{

FbConnectionStringBuilder cs = new FbConnectionStringBuilder();
cs.DataSource = sServerName.ToString();
cs.Database = sDatabaseName.ToString();
cs.UserID = "SYSDBA";
cs.Password = "masterkey";
cs.Dialect = 3;
string ConnectionString = cs.ToString();

SqlDataRecord record = new SqlDataRecord(
new SqlMetaData("field1", SqlDbType.SmallInt),
new SqlMetaData("field2", SqlDbType.NVarChar, 30));


SqlContext.Pipe.SendResultsStart(record);
DataTable dt = new DataTable();
FbConnection conn = new FbConnection(ConnectionString);
using (conn)
{
string ssql = "select field1, field2 from table1";
FbCommand command = new FbCommand(ssql, conn);
FbDataAdapter adapt = new FbDataAdapter(command);
conn.Open();
adapt.Fill(dt);

}

foreach (DataRow dr in dt.Rows)
{
record.SetValue(0, dr["field1"]);
record.SetValue(1, dr["field2"]);
SqlContext.Pipe.SendResultsRow(record);
}
SqlContext.Pipe.SendResultsEnd();
}

}

No comments: