Link to home
Start Free TrialLog in
Avatar of CyberUnDead
CyberUnDead

asked on

C# Insert Query, @@IDENTITY

What is wrong with my code below?  I am attempting to use the Microsoft Enterprise Library (DAAB) with Microsoft access.  My insert succeeds but I am uncertain on how to get the @@IDENTITY value back from the new record.  The return value is always zero.
public int SaveTicket(string organization, int category, DateTime openDate)
        {
            var database = DatabaseFactory.CreateDatabase();
            var query = "INSERT INTO Ticket ( Organization, Category, OpenDate ) SELECT @Organization, @Category, @OpenDate";
            var command = database.GetSqlStringCommand(query);
            database.AddInParameter(command, "@Organization", DbType.String, organization);
            database.AddInParameter(command, "@Category", DbType.Int32, category);
            database.AddInParameter(command, "@OpenDate", DbType.DateTime, openDate);
         
database.ExecuteNonQuery(command);
  
            var identity = database.GetSqlStringCommand("SELECT @@IDENTITY");
            return (int)database.ExecuteScalar(identity);
        }

Open in new window

Avatar of p_davis
p_davis

put that at the end of your inser

.....@OpenDate; Select @@Identity";

and executeScalar on your insert.
try using

var identity = database.GetSqlStringCommand("SELECT SCOPE_IDENTITY()");

Open in new window

Avatar of CyberUnDead

ASKER

Dear p_davis and zadeveloper I believe both methods are failing because my backend server is Microsoft Access.
Error-1.png
Error-2.png
it looks like you need to do it the way you were attempting before but you have to have an autoincrement field in the table for it to work.
you also need to use the same connection.
ASKER CERTIFIED SOLUTION
Avatar of CyberUnDead
CyberUnDead

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
did you try it with an autoincrement primary key? did that not work?
p_davis:
  TicketId is an autoincrement primary key in the Ticket table.
how about just running it as a query instead of scalar?
of course you will have to modify your return statement but you should be able to pull that new pk out.