我有一些代码可将数据插入并更新到sql表中。我使用ExecuteScalar来检查是否存在具有相同UserName和DeviceId的行。如果存在,我们将运行更新存储过程,并覆盖DataSource,PendingCount和LastUpdated字段。如果该行不存在,则使用插入存储过程。插入存储过程的效果很好,但更新存储过程似乎没有任何作用。该行保持不变。这是有问题的代码:
try
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand comm = new SqlCommand(query, sqlConnection))
{
comm.CommandType = System.Data.CommandType.Text;
comm.Parameters.Add(new SqlParameter("@DataSource", pending.DataSource));
comm.Parameters.Add(new SqlParameter("@LastUpdated", pending.LastUpdated));
comm.Parameters.Add(new SqlParameter("@PendingCount", pending.PendingCount));
comm.Parameters.Add(new SqlParameter("@DeviceId", pending.DeviceId));
comm.Parameters.Add(new SqlParameter("@UserName", pending.UserName));
int rowCount = (int)comm.ExecuteScalar();
if (rowCount > 0)
{
using (SqlCommand sqlComm = new SqlCommand("sp_UpdatePendingAttachments", sqlConnection))
{
sqlComm.CommandType = System.Data.CommandType.Text;
sqlComm.Parameters.Add(new SqlParameter("@DataSource", pending.DataSource));
sqlComm.Parameters.Add(new SqlParameter("@LastUpdated", pending.LastUpdated));
sqlComm.Parameters.Add(new SqlParameter("@PendingCount", pending.PendingCount));
sqlComm.Parameters.Add(new SqlParameter("@DeviceId", pending.DeviceId));
sqlComm.Parameters.Add(new SqlParameter("@UserName", pending.UserName));
}
}
else
{
using (SqlCommand sqlCommand = new SqlCommand("sp_InsertPendingAttachments", sqlConnection))
{
sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@DataSource", pending.DataSource));
sqlCommand.Parameters.Add(new SqlParameter("@UserName", pending.UserName));
sqlCommand.Parameters.Add(new SqlParameter("@DeviceId", pending.DeviceId));
sqlCommand.Parameters.Add(new SqlParameter("@PendingCount", pending.PendingCount));
sqlCommand.Parameters.Add(new SqlParameter("@LastUpdated", pending.LastUpdated));
sqlCommand.ExecuteNonQuery();
}
}
}
}
return new BaseResponse();
}
用于更新的存储过程是“ sp_UpdateStoredProcedure”:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_UpdatePendingAttachments]
(
-- Add the parameters for the stored procedure here
@DataSource VARCHAR(150) = '',
@DeviceId VARCHAR(150) = '',
@UserName VARCHAR(150) = '',
@PendingCount int = null,
@LastUpdated DateTime = null
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Insert statements for procedure here
UPDATE PendingAttachments
SET DataSource = @DataSource, PendingItemsCount = @PendingCount, LastUpdated = @LastUpdated
WHERE DeviceId = @DeviceId AND UserName = @UserName
END
GO
知道为什么更新行不起作用?存储过程或c#代码是否有问题?任何反馈表示赞赏!
您需要在所附图像中提到的位置上使用某些执行方法来执行Transact-SQL语句。您曾经使用ExecuteScaler()来找出现有记录,但是在更新时,您错过了添加任何执行方法的时间。