我正在使用旧工具和已经连接到此工具的数据库。我是新手,需要一些帮助来理解这一点。我需要帮助编写我尝试过的代码并且每次都出错。
public void UpdateUser(string NewUser, string OldUser)
{
using (SqlConnection con = HSDatabaseConnection())
{
using (SqlCommand cmd = new SqlCommand("UpdateNames", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("@LogonName", System.Data.SqlDbType.VarChar).Value = NewUser;
cmd.Parameters.Add("@OldLogonName", System.Data.SqlDbType.VarChar).Value = OldUser;
cmd.ExecuteNonQuery();
}
con.Close();
}
}
我有4个表,每个表的唯一共同点是列名" AN"。我需要更新" AN"如果代理人在法律上改变名称
到目前为止,我已经提出了这个程序
USE [HSDB]
GO
/****** Object: StoredProcedure [dbo].[UpdateNames] Script Date: 9/16/2016 12:32:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateNames]
--Add the parameters for the stored procedure here
@AN varchar(MAX)
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 Att
SET AN = @AN
WHERE (AN = @AN)
UPDATE MS
SET AN = @AN
WHERE (AN = @AN)
UPDATE Lost
SET AN = @AN
WHERE (AN = @AN)
UPDATE WeeklyCharges
SET AN = @AN
WHERE (AN = @AN)
END
有人可以告诉我我做错了什么。谢谢
答案 0 :(得分:0)
问题1: 你的c#代码正在传递2个参数@LogonName和@OldLogonName,但你的存储过程只接受1个参数@AN。所以这应该是错误的。
问题2: 所有的更新语句都将AN =设置为自身,因为你说当AN = @AN然后设置AN = @AN ....
如果没有关于错误和数据结构的更多详细信息(将来应该包含在内),则有点难以理解。但是,您可能可以在SQL-Server 2012 +中执行类似的操作:
USE [HSDB]
GO
/****** Object: StoredProcedure [dbo].[UpdateNames] Script Date: 9/16/2016 12:32:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateNames]
--Add the parameters for the stored procedure here
@LogonName varchar(100)
,@OldLogonName varchar(100)
AS
BEGIN
--SET NOCOUNT ON added to prevent extra result sets from
--interfering with SELECT statements.
SET NOCOUNT ON;
--Insert statements for procedure here
BEGIN TRY
IF NOT EXISTS (SELECT * FROM LogOnOrUserTable WHERE LogonName = @OldLogonName)
BEGIN
;THROW 51000, 'Old Logon Name Does Not Exists', 1
END
BEGIN TRANSACTION
UPDATE Att
SET AN = @LogonName
WHERE (AN = @OldLogonName)
UPDATE MS
SET AN = @LogonName
WHERE (AN = @OldLogonName)
UPDATE Lost
SET AN = @LogonName
WHERE (AN = @OldLogonName)
UPDATE WeeklyCharges
SET AN = @LogonName
WHERE (AN = @OldLogonName)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
;THROW
END CATCH
END
它的作用: