当我尝试运行此程序时,我得到一个 SqlException 消息“关键字'PROCEDURE'附近的语法不正确”。
120: cmd.CommandText = @"CREATE PROCEDURE FindState @Name nvarchar(50)
AS SELECT IDState FROM State WHERE Name=@Name";
121: cmd.ExecuteNonQuery();
堆栈跟踪:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at xxx.Program.Main(String[] args) in C:\xxx\Program.cs:line 121
但是我尝试直接在 SQL 查询中复制 SQL 命令并执行它并且它工作。(它创建了程序)
这里给你一些上下文是代码的一个更大的部分
SqlParameter stateName = new SqlParameter();
stateName.SqlDbType = SqlDbType.NVarChar;
stateName.Direction = ParameterDirection.Input;
stateName.ParameterName = "@Name";
stateName.Size = 50;
Console.Write("Enter state name: ");
stateName.Value = Console.ReadLine();
cmd.Parameters.Add(stateName);
cmd.CommandText = @"IF EXISTS (SELECT name FROM sysobjects WHERE name='FindState' AND type='P') DROP PROCEDURE FindState";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE PROCEDURE FindState
@Name nvarchar(50)
AS
SELECT IDState FROM State WHERE Name=@Name";
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "FindState";
sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
Console.WriteLine("ID state " + stateName.Value + " is " + sdr[0]);
}
}
else
{
Console.WriteLine("No such state exists");
}
sdr.Close();