I'm running a stored procedure inside a foreach loop in c#. After completion, all the rows of a column are getting updated with the top most value. Below is the stored procedure:
ALTER PROCEDURE [dbo].[getservername8]
@number varchar(255)
AS
DECLARE @server_name varchar(500)
SELECT @server_name = short_description
FROM [Event_alerts].[dbo].[event_alerts]
DECLARE @s AS varchar(50)
SELECT @s = SUBSTRING(@server_name, CHARINDEX('-', @server_name) + 15, 50)
UPDATE event_alerts
SET server_name = @s
WHERE number = @number
This is the C# code:
using (SqlCommand command2 = new SqlCommand("getservername8", conn))
{
command2.CommandType = CommandType.StoredProcedure;
command2.Parameters.AddWithValue("@number",number);
command2.Parameters["@number"].Direction = ParameterDirection.Input;
command2.ExecuteNonQuery();
}
Any help would be much appreciated
The culprit is because you are getting the same value of @server_name
for each call. So @s
si also same for all. that is why you are inserting the same value in the column
select @server_name = short_description from [Event_alerts].[dbo].[event_alerts]
declare @s as varchar(50)
select @s= SUBSTRING(@server_name, CHARINDEX('-', @server_name) + 15, 50)
Your code has a valid where
clause, so it should only be updating the matching rows. I can only speculate that all rows have the same value for number
.
However, you seem to have an error in the definition of @server_name
-- and that might be the problem you are referring to. There is no where
clause so it is set to an arbitrary value -- possibly from what you would call "the last row". Although that nomenclature is a misinterpretation of what happens.
Your SP is too complex anyway. I suspect that you intend:
alter procedure [dbo].[getservername8] (
@number varchar(255)
) as
begin
update ea
set server_name = substring(short_description, charindex('-', short_description) + 15, 50)
from event_alerts ea
where number = @number;
end; -- getservername8
Also note the good programming practices:
begin
/ end
. end
is tagged with the name of the SP.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.