我在获取最后一行受影响的 ID 时遇到问题,它返回 0,这意味着它在插入格式时出错。我执行了存储过程并手动添加了值,它返回了正确的 ID。但是,当我尝试使用代码执行此操作时,它会一直返回 0 或 -1 ...我昨晚在几个小时后尝试了此操作,但我已经对它给我的值感到困惑。
C#:
conn.Open();
cmd.Parameters.AddWithValue("@fileName", fileName);
cmd.Parameters.AddWithValue("@filePrivacy", filePrivacy);
cmd.Parameters.AddWithValue("@filePassword", filePassword);
cmd.Parameters.AddWithValue("@fileDescription", fileDesc);
cmd.Parameters.AddWithValue("@fileOwner", fileOwner);
cmd.Parameters.AddWithValue("@fileDate", DateTime.Now);
cmd.Parameters.AddWithValue("@fileExpire", DateTime.Now.AddMinutes(fileExpire));
cmd.Parameters.AddWithValue("@fileCodeText", fileType);
var fileID = cmd.Parameters.Add("@fileID", SqlDbType.Int);
fileID.Direction = ParameterDirection.Output;
int returnfileID = (int)cmd.ExecuteScalar();
return returnfileID;
存储过程:
CREATE PROCEDURE [dbo].[Upload]
@fileName nvarchar(20),
@filePrivacy int,
@filePassword nvarchar(50),
@fileDescription nvarchar(200),
@fileOwner nvarchar(14),
@fileDate smalldatetime,
@fileExpire smalldatetime,
@fileCodeText int,
@fileID int out
AS
INSERT INTO Files ([FileName], FilePrivacy, FilePassword, FileDescription, FileOwner, FileDate, FileExpire, FileCodeText)
VALUES (@fileName, @filePrivacy, @filePassword, @fileDescription, @fileOwner, @fileDate, @fileExpire, @fileCodeText)
SET @fileID = SCOPE_IDENTITY()
RETURN @fileID
SQL 表:
CREATE TABLE [dbo].[Files] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[FileName] NVARCHAR (20) NOT NULL,
[FilePrivacy] INT NOT NULL,
[FilePassword] NVARCHAR (50) NULL,
[FileDescription] NVARCHAR (200) NULL,
[FileOwner] NVARCHAR (14) NOT NULL,
[FileDate] SMALLDATETIME NOT NULL,
[FileExpire] SMALLDATETIME NOT NULL,
[FileCodeText] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);