Stored Procedure Doesn't work with C # code

I am trying to call a stored procedure in C #.

using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = connection.CreateCommand()) { command.CommandType = CommandType.StoredProcedure; command.CommandText = "updateData"; command.Parameters.Add(new SqlParameter("@inrego", rego)); command.Parameters.Add(new SqlParameter("@inOprt", oprt)); command.Parameters.Add(new SqlParameter("@inService", service)); connection.Open(); int update = command.ExecuteNonQuery(); Console.WriteLine(update); connection.Close(); } 

update shows 1 on the console, but the database is still not updating.

This is a stored procedure.

 CREATE PROCEDURE [dbo].updateData @inrego varchar(5), @inOprt char(3), @inService as varchar(50) AS delete from buses where rego = @inrego; insert into buses (rego, operator,service) values(@inrego, @inOprt, @inService); RETURN 0 

Starting a stored procedure manually works, aka

 USE [C:\USERS\---\DOCUMENTS\VISUAL STUDIO 2013\PROJECTS\---\TEST.DB.MDF] GO DECLARE @return_value Int EXEC @return_value = [dbo].[updateData] @inrego = N'1', @inOprt = N'2', @inService = N'3' SELECT @return_value as 'Return Value' GO 

works and successfully updates the database, but the C # code form does not work.

+5
source share
1 answer

I could not reproduce the problem in a clean local database (MS SQL EXPRESS 2013, Win 8.1, .NET 4.5):

 CREATE TABLE [dbo].buses ( [rego] varchar(5) NOT NULL PRIMARY KEY, [operator] char(3), [service] varchar(50) ) 
 static void UpdateOrInsertBuses(String rego, String oprt, String service) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = connection.CreateCommand()) { command.CommandType = CommandType.StoredProcedure; command.CommandText = "updateData"; command.Parameters.Add(new SqlParameter("@inrego", rego)); command.Parameters.Add(new SqlParameter("@inOprt", oprt)); command.Parameters.Add(new SqlParameter("@inService", service)); connection.Open(); try { int update = command.ExecuteNonQuery(); Console.WriteLine(update); } catch (Exception exc) { Console.WriteLine(exc.Message); } finally { connection.Close(); } } } } // ... // Add data UpdateOrInsertBuses("11", "12", "13"); UpdateOrInsertBuses("21", "22", "23"); // Update added UpdateOrInsertBuses("21", "22", "Changed for sure"); 

So, this is some problem that does not apply to your current code. As suggested by @Gordon Linoff, this is either a permission problem, or some kind of trigger that interferes with updates, or the database for some reason returns or ignores any changes.

+4
source

Source: https://habr.com/ru/post/1201511/


All Articles