【发布时间】:2020-07-16 20:50:47
【问题描述】:
我正在尝试使用存储过程将数据插入[AdventureWorks2017].[HumanResources].[Employee]。我已经测试了存储过程,它适用于我使用 C# 代码提供的值。
当我尝试对稍有不同的值(相同格式)执行相同操作时,代码不会引发异常或错误,但值不会反映在数据库中。我试过调试,所有变量都有要插入的值,并且与数据库的连接也打开了。
{
Employee employee = new Employee();
DateTime birthDate = new DateTime(1962, 07, 21);
DateTime hireDate = new DateTime(2000, 01, 01);
employee.RegisterEmployee("EM", 0, "Mr.", "Rakesh", "null", "Tripathi", "null", 0, "null", "null", "667567", "adventure-works\rakesh", "null", "Vice President of Engineering", birthDate, 'M', 'M', hireDate, 1, 100, 20, 1);
}
public int RegisterEmployee(string personType, int nameStyle, string title, string firstName, string middleName, string lastName, string suffix,
int emailPromotion, string additionalContactInfo, string demographics, string nationalIdNumber, string loginId, string organizationNode, string jobtitle,
DateTime dateOfBirth, char maritalStatus, char gender, DateTime hireDate, int salaried, int vacationHours, int sickLeaveHours, int currentFlag )
{
SqlCommand sqlCommand;
try
{
this.ConnectToDatabase();
this.sqlConnection.Open();
string commandText = "usp_RegisterNewEmployee";
sqlCommand = new SqlCommand(commandText, this.sqlConnection);
sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("@PersonType", personType);
sqlCommand.Parameters.AddWithValue("@NameStyle", nameStyle);
sqlCommand.Parameters.AddWithValue("@Title", title);
sqlCommand.Parameters.AddWithValue("@FirstName", firstName);
sqlCommand.Parameters.AddWithValue("@LastName", lastName);
sqlCommand.Parameters.AddWithValue("@JobTitle", jobtitle);
sqlCommand.Parameters.AddWithValue("@BirthDate", dateOfBirth);
sqlCommand.Parameters.AddWithValue("@EmailPromotion", emailPromotion);
sqlCommand.Parameters.AddWithValue("@MaritalStatus",maritalStatus);
sqlCommand.Parameters.AddWithValue("@Gender", gender);
sqlCommand.Parameters.AddWithValue("@HireDate", hireDate);
sqlCommand.Parameters.AddWithValue("@SalariedFlag", salaried);
sqlCommand.Parameters.AddWithValue("@VacationHours", vacationHours);
sqlCommand.Parameters.AddWithValue("@SickLeaveHours", sickLeaveHours);
sqlCommand.Parameters.AddWithValue("@CurrentFlag",currentFlag);
sqlCommand.Parameters.AddWithValue("@NationalIdNumber", nationalIdNumber);
sqlCommand.Parameters.AddWithValue("@LoginID", loginId);
if (middleName == "null")
sqlCommand.Parameters.AddWithValue("@MiddleName", DBNull.Value);
else
sqlCommand.Parameters.AddWithValue("@MiddleName", middleName);
if (suffix == "null")
sqlCommand.Parameters.AddWithValue("@Suffix", DBNull.Value);
else
sqlCommand.Parameters.AddWithValue("@Suffix", suffix);
if (additionalContactInfo == "null")
sqlCommand.Parameters.AddWithValue("@AdditionalContactInfo", DBNull.Value);
else
sqlCommand.Parameters.AddWithValue("@AdditionalContactInfo", additionalContactInfo);
if (demographics == "null")
sqlCommand.Parameters.AddWithValue("@Demographics", DBNull.Value);
else
sqlCommand.Parameters.AddWithValue("@Demographics", demographics);
if (organizationNode == "null")
sqlCommand.Parameters.AddWithValue("@OrganizationNode", DBNull.Value);
else
sqlCommand.Parameters.AddWithValue("@OrganizationNode", organizationNode);
SqlParameter BusinessEntityIdOutput = new SqlParameter("@BusinessEntityIdOutput", System.Data.SqlDbType.Int);
BusinessEntityIdOutput.Direction = System.Data.ParameterDirection.Output;
sqlCommand.Parameters.Add(BusinessEntityIdOutput);
SqlParameter returnValue = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
returnValue.Direction = System.Data.ParameterDirection.ReturnValue;
sqlCommand.Parameters.Add(returnValue);
int result = sqlCommand.ExecuteNonQuery();
Console.WriteLine("total rows affected:", result);
int businessEntityId = Convert.ToInt32(BusinessEntityIdOutput.Value);
Console.WriteLine("Business entity id: " + businessEntityId);
}
catch (Exception e)
{
Console.WriteLine("Some error occurred...");
Console.WriteLine(e.Message);
}
finally
{
this.sqlConnection.Close();
}
return 0;
}
我试图从1、2 和3 中找到解决方案,但这些不适用于我的情况。
下面是我用来插入值的存储过程。
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_RegisterNewEmployee]
(
/*Parameters required for person*/
@PersonType [nchar](2),
@NameStyle [dbo].[NameStyle] = 0,
@Title [nvarchar](8),
@FirstName [dbo].[Name],
@MiddleName [dbo].[Name],
@LastName [dbo].[Name],
@Suffix [nvarchar](10),
@EmailPromotion [int],
@AdditionalContactInfo [xml] = NULL,
@Demographics [xml] = NULL,
/*Parameters required for Employee*/
@NationalIdNumber [nvarchar](15),
@LoginID [nvarchar](256),
@OrganizationNode [hierarchyid],
@JobTitle [nvarchar](50),
@BirthDate [date],
@MaritalStatus [nchar],
@Gender [nchar],
@HireDate [date],
@SalariedFlag [dbo].[Flag],
@VacationHours [smallint],
@SickLeaveHours [smallint],
@CurrentFlag [dbo].[Flag],
@BusinessEntityIdOutput INT OUT
)
AS
SET NOCOUNT ON;
BEGIN
BEGIN TRY
BEGIN TRANSACTION
DECLARE @BusinessEntityID INT
/* Enter new business entity id column in Person.BusinessEntity table */
INSERT INTO [AdventureWorks2017].[Person].[BusinessEntity]
VALUES (NEWID(), GETDATE());
SELECT @BusinessEntityID = SCOPE_IDENTITY();
SET @BusinessEntityIdOutput = @BusinessEntityID;
/* Register the same person in Person.Person table */
INSERT INTO [AdventureWorks2017].[Person].[Person]
(
[BusinessEntityID],
[PersonType],
[NameStyle],
[Title],
[FirstName],
[MiddleName],
[LastName],
[Suffix],
[EmailPromotion],
[AdditionalContactInfo],
[Demographics],
[rowguid],
[ModifiedDate]
) VALUES
(
@BusinessEntityID,
@PersonType,
@NameStyle,
@Title,
@FirstName,
@MiddleName,
@LastName,
@Suffix,
@EmailPromotion,
@AdditionalContactInfo,
@Demographics,
NEWID(),
GETDATE()
)
/* Input the new row in the HumanResources.Employees table */
INSERT INTO [HumanResources].[Employee]
(
[BusinessEntityID],
[NationalIDNumber],
[LoginID],
[OrganizationNode],
[JobTitle],
[BirthDate],
[MaritalStatus],
[Gender],
[HireDate],
[SalariedFlag],
[VacationHours],
[SickLeaveHours],
[CurrentFlag],
[rowguid],
[ModifiedDate]
)
VALUES
(
@BusinessEntityID,
@NationalIdNumber,
@LoginID,
@OrganizationNode,
@JobTitle,
@BirthDate,
@MaritalStatus,
@Gender,
@HireDate,
@SalariedFlag,
@VacationHours,
@SickLeaveHours,
@CurrentFlag,
NEWID(),
GETDATE()
)
COMMIT
--RETURN @BusinessEntityIdOutput
END TRY
BEGIN CATCH
ROLLBACK;
RETURN -99
END CATCH
END
【问题讨论】:
-
那么哪些值有效,哪些值无效?
-
我强烈建议您将所有
AddWithValue替换为Add,并使用正确的数据类型自己构建SqlParameter。使用AddWithValue时有很多problems。 -
我们可能还需要查看您的 SP 代码。
-
一些一般性建议: 1. 将
RegisterEmployee更改为接受一个类(模型)并拥有现在有多个方法参数的属性。示例:public class EmployeeModel { public string Title {get; set; } }。 2.不要用"null"代替`null',那也是自找麻烦。 3. 对诸如 personType 之类的值可能仅限于特定子集的事物使用枚举或其他约束。最后不要使用“AddWithValue”,而是使用 Add 并包括数据类型和长度(如果适用)。 -
完全不相关,但是,您的结果将始终为 0。
标签: c# sql-server ado.net