Search code examples
c#sqlssisinsertscript-task

Must declare the scalar variable "@ID" error, C#, SSIS, in Script task


This is driving me nuts. Probably it is something silly I can't see.

This is my code:

cnnDbLocal = new OleDbConnection(localDbStringConnection);
cnnDbLocal.Open();
string select = "INSERT INTO Estimate (EstimateID) VALUES (@IdVal);";
using (OleDbCommand command = new OleDbCommand(select, cnnDbLocal)) { 
    command.Parameters.AddWithValue("@IdVal", 1);
    rowsAffected = command.ExecuteNonQuery();
}

And I keep getting the error: {"Must declare the scalar variable "@IdVal"."}

I can't believe I cannot figure this out. I tried using the Add() method, but apparently, it is deprecated.

I don't think it is a DB problem, but the code is here anyway:

CREATE TABLE [dbo].[Estimate](
    [EstimateID] [int] NULL,
    [Name] [varchar](50) NULL,
    [Description] [varchar](200) NULL,
    [Weight] [float] NULL,
    [FacilityID] [smallint] NULL,
    [JDEFacility] [smallint] NULL,
    [FabricationHours] [float] NULL,
    [CreatedOn] [datetime] NULL
) ON [PRIMARY]
GO

Thank you for opening my eyes, I am so frustrated this afternoon.


Solution

  • OleDB does not support named parameters. You need to use a ? and pass the parameters in the correct order. Adjustments made below.

    Using (OleDbConnection db = new OleDbConnection(localDbStringConnection)) {
        db.Open();
        using (OleDbCommand cmd = new OleDbCommand()) {
            cmd.commandText = "INSERT INTO Estimate (EstimateID) VALUES (?);";
            cmd.connection = db;
            cmd.Parameters.Add("@IdVal", OleDbType.Integer).value = 1;
            rowsAffected = cmd.ExecuteNonQuery();
        }
    }