SQL/C#获取受Insert影响的行的ID
本文关键字:影响 ID Insert 获取 SQL | 更新日期: 2023-09-27 18:19:57
我正在尝试"实时"获取受影响行的ID。我可以检查它是否使用了参数或最后一行,但我希望尽可能减少延迟,这样就不会有多个用户在表中混合信息。
迄今为止已尝试:
public int setFileInfo(string fileName, int filePrivacy, string filePassword, string fileDesc, string fileOwner)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["bitRain"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("dbo.Upload", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
if(!String.IsNullOrEmpty(filePassword))
{
filePassword = FormsAuthentication.HashPasswordForStoringInConfigFile(filePassword, "MD5");
}
try
{
conn.Open();
cmd.Parameters.Add("@fileName", fileName);
cmd.Parameters.Add("@filePrivacy", filePrivacy);
cmd.Parameters.Add("@filePassword", filePassword);
cmd.Parameters.Add("@fileDescription", fileDesc);
cmd.Parameters.Add("@fileOwner", fileOwner);
int fileID = (int)cmd.ExecuteScalar();
return fileID;
}
catch (Exception ex)
{ }
finally
{
conn.Close();
}
return -1;
}
}
存储过程:
CREATE PROCEDURE [dbo].[Upload]
@fileName nvarchar(20),
@filePrivacy int,
@filePassword nvarchar(50),
@fileDescription nvarchar(200),
@fileOwner nvarchar(14)
AS
INSERT INTO Files ([FileName], FilePrivacy, FilePassword, FileDescription, FileOwner)
VALUES (@fileName, @filePrivacy, @filePassword, @fileDescription, @fileOwner)
RETURN 0
我需要一些OUTPUT参数,但我不知道如何使用它,msdn示例对我来说也不够清楚。
存储过程:
CREATE PROCEDURE [dbo].[Upload]
@fileName nvarchar(20),
@filePrivacy int,
@filePassword nvarchar(50),
@fileDescription nvarchar(200),
@fileOwner nvarchar(14),
@id int out
AS
INSERT INTO Files ([FileName], FilePrivacy, FilePassword, FileDescription, FileOwner)
VALUES (@fileName, @filePrivacy, @filePassword, @fileDescription, @fileOwner)
set @id = SCOPE_IDENTITY()
END
在cs中添加
cmd.Parameters["@id"].Direction = ParameterDirection.Output;
尝试使用SCOPE_IDENTITY函数