TSQL使用c#创建存储过程

时间:2016-07-30 03:34:08

标签: c# sql-server tsql stored-procedures

我正在尝试在我的.net项目中创建一个过程(删除一个过程并用新数据重新创建它)。当我在数据库“创建新查询”中运行相同的查询时它工作正常,但当我尝试在c#中运行它时,它给了我一个错误。

This is the successful query completed when i run it on Database

private void makeprocedure()
            {
                string sqlProcedureCreate = @"
    IF(OBJECT_ID('usp_HourData') IS NOT NULL)
        DROP PROCEDURE IF EXISTS usp_HourData;
    GO

    CREATE PROCEDURE usp_HourData
    AS
    BEGIN

    SELECT Employee.[First Name] + ' ' + Employee.[Last Name] AS 'Name',
     sum(Time.[Total Hours]) AS 'Total Hours'
     , FORMAT(Time.[Time in], 'd', 'en-gb') AS 'Worked On'
     FROM Employee
     inner join Time on
     Employee.ID ='" + getID() + "' and Time.EmployeeIdFK = '" + getID()
     + "' WHERE Time.[Time in] between '" + CalendarStart.SelectedDate + "' and '" + CalendarEnd.SelectedDate
     + @"'GROUP BY FORMAT(Time.[Time in], 'd', 'en-gb') ,Employee.[First Name] + ' ' +Employee.[Last Name];
     END     
     ";
                using (SqlCommand command = new SqlCommand(sqlProcedureCreate, con))
                {
                    command.CommandType = CommandType.Text; //I tried command.CommandType = CommandType.StoredProcedure;
                        con.Open();
                        command.ExecuteNonQuery(); //Compiler says error is on this line
                        con.Close();
                }
            }

错误接近“GO”,“CREATE / ALTER PROCEDURE”必须先行。

System.Data.SqlClient.SqlException was unhandled by user code
  Class=15
  ErrorCode=-2146232060
  HResult=-2146232060
  LineNumber=4
  Message=Incorrect syntax near 'GO'.
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
  Number=102
  Procedure=""
  Server=(LocalDB)\MSSQLLocalDB
  Source=.Net SqlClient Data Provider
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at WebApplication2.Manager.makeprocedure() in D:\Users\Albin\MyClockIn\WebApplication2\WebApplication2\Manager.aspx.cs:line 209
       at WebApplication2.Manager.ButtonSearch_Click(Object sender, EventArgs e) in D:\Users\Albin\MyClockIn\WebApplication2\WebApplication2\Manager.aspx.cs:line 161
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

我该如何处理此错误?

1 个答案:

答案 0 :(得分:0)

这可能不是您问题的答案,而只是对您的编程风格的建议。这些都是代码中的坏事:

  1. 您正在连接查询字符串。你应该使用参数。
  2. 您正在创建一个过程,其中查询包含数据而不是参数。存储过程应该包含带参数的查询,您应该将数据传递给它。
  3. 每次访问时都不应删除和重新创建存储过程。我可以清楚地看到,只需使用select语句就可以获得相同的结果。如果要创建存储过程,则必须传递一些数据,否则无法进行存储过程。

    足够的理论,让我们看看实际行动:

    以下是您的MakeProcedure(请重命名)功能:

    //Rename this function to some useful name
    private void makeprocedure()
    {
        string query = @" SELECT Employee.[First Name] + ' ' + Employee.[Last Name] AS 'Name',
    sum(Time.[Total Hours]) AS 'Total Hours'
    , FORMAT(Time.[Time in], 'd', 'en-gb') AS 'Worked On'
    FROM Employee
    inner join Time on
    Employee.ID = @EmpId and Time.EmployeeIdFK = @EmpId WHERE Time.[Time in] 
    between @StartDate and @EndDate GROUP BY FORMAT(Time.[Time in], 'd', 'en-gb'),
    Employee.[First Name] + ' ' +Employee.[Last Name];";
    
    
        using (SqlCommand command = new SqlCommand(query, con))
        {
            command.CommandType = CommandType.Text;
            command.Parameters.AddWithValue("@EmpId", getID());
            command.Parameters.AddWithValue("@StartDate", CalendarStart.SelectedDate);
            command.Parameters.AddWithValue("@EndDate", CalendarEnd.SelectedDate);
            con.Open();
            var reader = command.ExecuteReader();
            //do something with data in the reader.
            con.Close();
        }
    }