0

我正在尝试“实时”获取受影响的行的 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 示例对我来说还不够清楚。

4

2 回答 2

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;
于 2013-06-26T17:13:05.857 回答
2

尝试使用SCOPE_IDENTITY函数

于 2013-06-26T17:14:31.967 回答