我需要知道我是否正确编写了存储过程以及用于执行的 C# 代码是否正确。由于某种原因,返回的错误是“c16b”附近的语法不正确。旧错误
现在的新错误是:过程或函数“sptimeupdate”需要未提供的参数“@date”。
ClientID列中用于验证和更新的nvarchar字符串为3fc8ffa1-c16b-4d7b-9e55-1e88dfe15277,但粗体部分仅显示在错误处理中的调试测试intel sense
ALTER PROCEDURE sptimeupdate
@id nvarchar(50),
@date datetime
AS
BEGIN
SET NOCOUNT ON;
UPDATE ClientTable
SET Today_Date=(@date)
WHERE ClientID=(@id)
END
//--------------above stored procedure--------------------------------
//--------------Executing the stored procedure in C#
IEnumerable<XElement> searchClientID =
from clientid in main.XPathSelectElements("Network/ClientID")
where (string)clientid.Attribute("id") == IntializedPorts[i].ToString()
select clientid;
foreach (string clientid in searchClientID)
{
for (int up = 0; up < IntializedPorts.Count(); up++)
{
//Update the current time in the clientid tble.
//Renames the table copy for groups
try
{
string[] Clientid; //client id array
Clientid = new string[IntializedPorts.Count()]; //Intialization of the array
Clientid[up] = clientid.ToString();
DateTime td = Convert.ToDateTime(toolDate.Text); //Just added a datetime object withdate
SqlConnection sqlConnectionCmdString = new SqlConnection(@"Data=.\SQLEXPRESS;AttachDbFilename=C:\Users\Shawn\Documents\Visual Studio 2010\Projects\Server\database\ClientRegit.mdf;Integrated Security=True;User Instance=True");
//EXECUTE THE STORED PROCEDURE sptimedate
// string UpdateCommand = "sptimeupdate" + Clientid[up].ToString() + toolDate.Text;
string UpdateCommand = "sptimeupdate" + "'" + Clientid[up].ToString() + "'" + "'" +td.ToString()+ "'"; //this is the new UpdateCommand string as to pass parameters to stored procedure
SqlCommand sqlRenameCommand = new SqlCommand(UpdateCommand, sqlConnectionCmdString);
sqlConnectionCmdString.Open();
sqlRenameCommand.ExecuteNonQuery();
sqlConnectionCmdString.Close();
}
catch(DataException ex)
{ MessageBox.Show("Failed to UpdateCurrentTime","DataError",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
请您参考如下方法:
当您从代码中调用存储过程时,您需要创建一个命令并将其命令类型设置为 StoredProcedure,否则引擎会尝试使用您的命令文本,因为它是一个 sql 文本,如 SELECT INSERT 等...但是 mose重要的是你需要在命令的Parameters集合中传递存储过程需要的参数
所以这可能是替换实际代码的代码
string UpdateCommand = "sptimeupdate";
using(SqlConnection sqlConnectionCmdString = new SqlConnection(......))
using(SqlCommand sqlRenameCommand = new SqlCommand(UpdateCommand, sqlConnectionCmdString))
{
DateTime td = Convert.ToDateTime(toolDate.Text);
sqlRenameCommand.CommandType = CommandType.StoredProcedure;
sqlRenameCommand.Parameters.Add("@id", SqlDbType.NVarChar).Value = Clientid[up].ToString();
sqlRenameCommand.Parameters.Add("@date", SqlDbType.DateTime).Value = td;
sqlConnectionCmdString.Open();
sqlRenameCommand.ExecuteNonQuery();
}
注意两件事。 using 语句是创建连接时要遵循的最佳实践,以确保正确关闭和处理连接,其次,sp 预期的 DateTime 参数应作为 DateTime 而不是字符串传递 - 当然这意味着您应该确定 toolDate 的内容可以转换为 DateTime 值。
