2 回答

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
這里我們用C#做一個(gè)計(jì)算滑輪系統(tǒng)近似距離的函數(shù),并把該函數(shù)部署到SqlServer2005上去,這里使用的方法是原始的,全手動(dòng)方式的部署方式,主要的目的是為了理解部署原理,實(shí)際上直接開SqlServer數(shù)據(jù)庫項(xiàng)目可能更容易些。
首先讓我們看一下滑輪傳輸帶系統(tǒng)圖示,如下圖所示:
用C#編寫SQLServer自定義函數(shù)
一、首先在VS2005里編寫一個(gè)計(jì)算傳輸帶距離的函數(shù),源代碼如下所示:
//自定義計(jì)算傳輸帶距離的函數(shù)
using System;
using System.Collections.Generic;
using System.Text;
namespace SqlServerClr
{
public class pulley
{
public static double PulleyDistance(double Pulley1Diameter, double Pulley2Diameter, double BeltLength)
{
double length = 0, a = 2.0;
double b = BeltLength - 1.57 * (Pulley1Diameter + Pulley2Diameter);
double c = System.Math.Pow(Pulley1Diameter - Pulley2Diameter, 2.0);
//如果只是
double b1 = (b * b) - (4 * a * c);
if (b1 > 0)
{
length = (b + Math.Sqrt(b1)) / (2 * a);
//檢查傳輸帶是否合適
if (length < ((Pulley1Diameter + Pulley2Diameter) / 2))
{
//返回0,如果傳輸帶不合適;
length = 0;
}
}
//精度只允許一位小數(shù)
return System.Math.Round(length, 1);
}
}
}
把以上CS文件編譯為動(dòng)態(tài)連接庫, 在Visual Studio 2005 命令行模式下使用命令:
csc /t:library /out:pulleylib.dll pulley.cs
編譯成功,得到了一個(gè)pulleylib.dll
二、在SQL Sever 2005中部署CS的自定義函數(shù)
--編譯PulleyDistance函數(shù)
Drop Assembly Mechanics --如果編譯程序出錯(cuò)可以用此命令刪除程序集
Create Assembly Mechanics --Mechanics是編譯程序集名稱
from 'E:\pulleyLib.dll'
Go
Create function PulleyDistance
(
@diameter1 float,
@diameter2 float,
@beltLength float
)
--注意這里的三個(gè)參數(shù)名稱可以和CS編寫的靜態(tài)函數(shù)不同,但類型要兼容一致
returns float
As External name
[Mechanics].[SqlServerClr.pulley].[PulleyDistance]
--CS中定義的靜態(tài)函數(shù)全稱一般為【命名空間.類名】.【函數(shù)名】,注意這里是區(qū)分大小寫的,對應(yīng) [SqlServerClr.pulley].[PulleyDistance]
GO
--檢查是否已經(jīng)部署上了
select dbo.PulleyDistance(3,2,100)
--檢查部署結(jié)果
select routine_name,routine_body from information_schema.routines
通過以上兩步,一個(gè).NetCLR的函數(shù)就部署到了SqlServer上了

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
//定義
SqlConnection conn = new SqlConnection(DbTool.getSQLConnString());
string strSql = "AutoNum"; //" and user_role='Administrator'";
SqlCommand cmd = new SqlCommand(strSql, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@cust_name",SqlDbType.NVarChar).Value="";
cmd.Parameters.Add("@returnString", SqlDbType.NVarChar);
cmd.Parameters["@returnString"].Direction = ParameterDirection.ReturnValue;
string strRTN = "";
//方法
try
{
conn.Open();
object o= cmd.ExecuteScalar();
strRTN = cmd.Parameters["@returnString"].Value.ToString();
}
catch (Exception ex)
{
LabelTestMSG.Text = ex.Message;
}
finally
{
if (!(conn.State == ConnectionState.Closed))
{
conn.Close();
}
}
}
--------------
其實(shí)有個(gè)更簡單的方法,你把函數(shù)封裝到存儲(chǔ)過程里,用exec的語句直接跟select語句一樣的調(diào)用.
- 2 回答
- 0 關(guān)注
- 113 瀏覽
添加回答
舉報(bào)