我遇到了最後一行受影響的ID問題,它返回0,這意味着它在插入格式時出錯。我執行了存儲過程並手動添加了值,它返回了正確的ID。但是當我試圖用代碼來實現它時,它會一直返回0或-1 ......我昨晚在幾個小時後嘗試了這一點,而且我已經對它給予我的值感到困惑。SQL Scope_Identity正在返回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)
);
你已經聲明'fileID'是一個'OUTPUT'參數,但你永遠不會從它獲得值。 –