简体   繁体   中英

C# SQL output code issue

I am having an issue with the code below, I keep getting

"Procedure or function 'InsertFile' Expects parameter '@ID', which was not supplied"

I must be doing something wrong in the returning of the ID.

ALTER PROCEDURE [dbo].[InsertFile] 
-- Add the parameters for the stored procedure here
    --@AssetID INT,
    @ComputerName varchar(max),
    @FilePath varchar(max),
    @Owner varchar(100),
    @Size int,
    @Extension varchar(50),
    @CreationDate datetime,
    @ModifiedDate datetime,
    @AccessedDate datetime,
    @ID int output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

IF NOT EXISTS (SELECT * From DC_Files Where computerName = @ComputerName AND FilePath = @FilePath)
BEGIN   
    INSERT INTO DC_Files (ComputerName, FilePath, Owner, Size, Extension, CreationDate, ModifiedDate, AccessedDate)
        VALUES (@ComputerName, @FilePath, @Owner, @Size, @Extension, @CreationDate, @ModifiedDate, @AccessedDate)
END
ELSE
BEGIN
    UPDATE DC_Files
    SET Owner = @Owner, Size = @Size, CreationDate = @CreationDate, ModifiedDate = @ModifiedDate, AccessedDate = @AccessedDate
    WHERE computerName = @ComputerName AND FilePath = @FilePath
END
SET @ID = SCOPE_IDENTITY()
END

The C# code:

SqlCommand cmd = new SqlCommand("InsertFile",conn);
cmd.CommandType = CommandType.StoredProcedure;

//cmd.Parameters.AddWithValue("@AssetID", FileInfo);
cmd.Parameters.AddWithValue("@ComputerName", Environment.MachineName);
cmd.Parameters.AddWithValue("@FilePath", FilePath);
cmd.Parameters.AddWithValue("@Owner", FileSecurity.GetOwner(typeof(NTAccount)).Value);
cmd.Parameters.AddWithValue("@Size", FileInfo.Length);
cmd.Parameters.AddWithValue("@Extension", FileInfo.Extension);
cmd.Parameters.AddWithValue("@CreationDate", FileCreationTime);
cmd.Parameters.AddWithValue("@ModifiedDate", FileModifiedTime);
cmd.Parameters.AddWithValue("@AccessedDate", FileAccessedTime);
var returnParameter = cmd.Parameters.Add("@ID", SqlDbType.Int);
cmd.ExecuteNonQuery();

You have to set the Direction to Output since by default the Direction of all Parameter is Input.

      // Create parameter with Direction as Output
       SqlParameter returnParameter = new SqlParameter("@ID", SqlDbType.Int)
       { 
          Direction = ParameterDirection.Output 
       };

   cmd.Parameters.Add(returnParameter);

Try Adding output parameter as follows in ur C# code

SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "@ID";
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;

outPutParameter.Direction = System.Data.ParameterDirection.Output;

 cmd.Parameters.Add(outPutParameter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM