fypoop

博客园 首页 新随笔 联系 订阅 管理

刚转到VS2005和SQL2005上,研究了一下怎么在vs2005中写存储过程
以下是我写的代码
首先新建一个


确定之后会让你选择数据联结







如果默认的数据库没有,可以用add refrence添加

之后再在解决方案中添加一个StoredProcedure项目
下面是代码
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Data.Sql;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    [SqlProcedure]
    public static void Hello()
    {
        SqlContext.Pipe.Send("hello ,fypoop!");
       
    }

    [SqlProcedure]
    public static void InsertData(SqlString name)
    {
        
       using (SqlConnection conn = new SqlConnection("context connection=true"))
  {
   conn.Open();
   SqlCommand cmd = new SqlCommand();
   cmd.CommandType = CommandType.Text;
   cmd.Connection = conn;
   cmd.CommandText = "INSERT INTO BIProperty ([Type], [Count],[Desc]) VALUES ('" + name.Value + "',1, '" + DateTime.Now.ToString() + "')";  
      cmd.ExecuteNonQuery();
  }
        
    }

    [SqlFunction]
    public static SqlString testFunction()
    {
        return "hello , fypop.cnBlogs.com";
    }

    [SqlProcedure]
    public static void GetTitlesByAuthor(string flag)
    {
        string sql = "select * from AnswerContentAndScore where flag=@flag";
        using (SqlConnection conn = new SqlConnection("context connection=true"))
        {
            conn.Open();
            SqlPipe sp = SqlContext.Pipe;
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            cmd.CommandText = sql;
            SqlParameter paramauthorID = new SqlParameter("@flag", SqlDbType.Int);
            paramauthorID.Direction = ParameterDirection.Input;
            paramauthorID.Value = flag;
            cmd.Parameters.Add(paramauthorID);
            SqlDataReader rdr = cmd.ExecuteReader();
            sp.Send(rdr);
        }

    }
};

说明
SqlConnection("context connection=true")是表示用当前登录SQL Server的用户来开连接,进行操作
SqlContext 从服务器端把消息,结果集返回到客户端

这时候你就可以用EXEC SqlProcedure 来跑你自己的存储过程了
理解有限,所以写的也有限,大家看看就好了

忘了说一点,如果你的SQL2005服务器不支持clr ,那就运行一下下面的存储过程
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO 
 
 EXEC sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO 
 
 

要关闭clr enabled,可以使用

EXEC sp_configure 'clr enabled', 0
GO
RECONFIGURE
GO

posted on 2006-07-18 11:28  冰冷  阅读(1390)  评论(0编辑  收藏  举报