从代码创建存储过程 - C#

时间:2016-03-11 14:18:14

标签: c# sql-server stored-procedures

我在SQL Server数据库中创建存储过程时遇到问题。这就是我要做的事情:

public void selectMeetings(String PID)
{
    String connection = "Server=localhost;Database=master;Integrated security=true;";
    SqlConnection Connection = new SqlConnection();

    Connection = new SqlConnection(connection);
    Connection.Open();

    string script = "USE ["+PID+ "] GO CREATE PROCEDURE selectMeetings AS SELECT * FROM dbo.MEETING GO";

    SqlCommand command = new SqlCommand(script, Connection);

    try
    {
       command.ExecuteNonQuery();
    }
    catch (System.Exception ex)
    {
        throw ex;
    }
}

问题在于:

  

' GO'附近的语法不正确   '创建/更改程序'必须是查询批处理中的第一个语句

我试图删除GO,但问题是:

  

'创建/更改程序'必须是查询中的第一个语句   批次。

如何解决这个问题?感谢

1 个答案:

答案 0 :(得分:3)

client code切换数据库,正如其他人所说,不发送GO,因为它是一个T-SQL命令:

public void selectMeetings(String PID)
{
    String connection = "Server=localhost;Database=master;Integrated security=true;";
    SqlConnection Connection = new SqlConnection();

    Connection = new SqlConnection(connection);
    Connection.Open();

    Connection.ChangeDatabase(PID);

    string script = "CREATE PROCEDURE selectMeetings AS SELECT * FROM dbo.MEETING";
    SqlCommand command = new SqlCommand(script, Connection);

    //You're not fishing. There's no point in catch and release
    command.ExecuteNonQuery();
}

进一步修复最佳做法:

public void selectMeetings(String PID)
{
    String connection = "Server=localhost;Database=master;Integrated security=true;";
    using(SqlConnection Connection = new SqlConnection(connection))
    {
      Connection.Open();

      Connection.ChangeDatabase(PID);

      string script = "CREATE PROCEDURE selectMeetings AS SELECT * FROM dbo.MEETING";
      using(SqlCommand command = new SqlCommand(script, Connection))
      {
        command.ExecuteNonQuery();
      }
    }
}