本文以Visual Studio 2008为例。

步骤:

1. 打开 Visual Studio 2008

2. New Project,选择 Visual C# –> Database –> SQL Server Project.

3. 设置 Project Name 为 MyClrProcTest,并点击 Ok.

4. 弹出对话框 “Add Database Reference”,找到并选中你的数据库然后确认.

5. 在 Solution Explorer 栏目中,右键点击 MyClrProcTest 工程-> Add –> Stored Procedure.

6. 弹出对话框 “Add New Item”,输入存储过程文件名为 sp_MyClrProc.cs,点 Add 确认.

7. 用以下代码替换:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void sp_MyClrProc(string name)
    {
        using (SqlConnection conn = new SqlConnection("context connection=true"))
        {
            SqlCommand cmd = new SqlCommand();
            SqlParameter param = new SqlParameter("@Name", SqlDbType.NVarChar);

            param.Value = name;
            cmd.Parameters.Add(param);
            cmd.CommandText = "select 'Hello: ' + @Name as [Greeting]";
            cmd.Connection = conn;
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            SqlContext.Pipe.Send(dr);
            conn.Close();
        }
    }
};

8. 编辑工程自动生成的SQL测试文件 Test.sql,在文件末添加一行

exec sp_MyClrProc @Name='Mike'

9. 在运行上面的测试代码前先要启用 CLR 功能,在SQL Server Management Studio中运行如下命令:

sp_configure 'clr enabled', 1
reconfigure

10. 回到之前的工程 MyClrProc,按F5运行,观察输出内容

Greeting   
-----------
Hello: Mike

 

这样整个CLR存储过程就已经成功部署。

posted on 2012-04-12 11:13  YUVU  阅读(407)  评论(0编辑  收藏  举报