Ron
Ron

Reputation: 2503

Sql requires scalar to be declared

The following sql (Sql Server 2016) generates an error:

INSERT INTO Requests (EntryDate,Status, AccountID)
VALUES (@EntryDate,@Status,@accountID)"; 
        try
        { 
            DatabaseConnection.Execute(sql,
    new
    {             
        DateTime.Now,
        Status = (int)Status.New, '''an enum
        accountID,             
    }, this.Transaction);

This generates the error:

 Must declare scalar variable @EntryDate.

If I replace @EntryDate with getdate(), this runs OK. Even though it seems that getdate() is not used. Why this one value?

Upvotes: 0

Views: 261

Answers (1)

Jeroen Mostert
Jeroen Mostert

Reputation: 28809

@EntryDate is a parameter of your command. You must supply it as such, even if the value is unused, otherwise SQL Server will look for a variable named @EntryDate (which likewise doesn't exist).

If you write new { DateTime.Now, ... } you are passing an anonymous object with a property named Now, which can't be mapped to the actual parameter. Change DateTime.Now to EntryDate = DateTime.Now so the name matches up. The question doesn't specify which object-relational mapper you are using (Dapper?) but they will all need to pass named parameters somehow.

Upvotes: 1

Related Questions