我正在尝试“实时”获取受影响的行的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示例对我来说还不够清楚。
答案 0 :(得分:7)
存储过程:
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;
答案 1 :(得分:2)
尝试使用SCOPE_IDENTITY功能