user1552172 user1552172 - 2 months ago 14
C# Question

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();

Answer

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);
Comments