C#编写SQL Server 2005/2008存储过程

大致分为两个步骤:

1. 用C#开发类库

建立一个普通的类库项目,下面是一个实例:

   using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.SqlServer.Server;
    namespace com.shangsi.ShsSqlUtility
    {
        public class SqlEncoding
        {
            public SqlEncoding()
            {

            }
            [SqlFunction(DataAccess = DataAccessKind.None)]
            /// <summary>
            /// 内码转换
            /// </summary>
            /// <param name="encode"></param>
            /// <returns></returns>
            public static string ConvertPageCode(string OriginalStr, int FromCodePage, int ToCodePage)
            {
                if (OriginalStr == null) return null;

                OriginalStr = OriginalStr.Trim();
                if (OriginalStr == "") return "";

                Encoding TargetEncoding = Encoding.GetEncoding(ToCodePage);
                Encoding OriginalEncoding = Encoding.GetEncoding(FromCodePage);//("iso8859-1"); //在SQL Server 查询分析器中输入sp_helpsort 可以看到SQL Server存储使用的字符集合
                Byte[] OriginalBytes = OriginalEncoding.GetBytes(OriginalStr);
                return TargetEncoding.GetString(OriginalBytes);
            }
        }
    }

2. 把函数注册到SQL Server中

drop assembly [com.shangsi.ShsSqlUtility]

create assembly [com.shangsi.ShsSqlUtility]
FROM 'd:\lib\ShsSqlUtility.dll'

drop function ConvertCP
CREATE FUNCTION ConvertCP(@OriginalStr nvarchar(1000),@FromCodePage int, @ToCodePage int) 
RETURNS nvarchar(800)
AS
External name [com.shangsi.ShsSqlUtility].[com.shangsi.ShsSqlUtility.SqlEncoding].ConvertPageCode

EXEC sp_configure 'clr enabled',1
go
RECONFIGURE 
go

select dbo.ConvertCP(null, 936, 1252)

如果不支持“Extrnal”需更改数据库的兼容性至少到SQL Server2005