0

I am now searching for a while not finding a solution for my problem. I would like to insert a new row into a table if it currently not exists. I need the auto-incremented key of that new entry or the existing key of the existing entry.

Also I'm not clear about the idea of the return-value of my INSERT, what if one column is inserted, value = 1, and what if the row exists? value = 0 or NULL or ?!

If possible I do NOT want to "BATCH-INSERT", I must use these two return-values for the next INSERT as foreign keys... or has anyone an idea how to do this all with batch inserts?

Thanks to everybody who can help!!

System: MS SQL 2012 standard database, JAVA SE 1.6, sqljdbc4

This is my code, that gives me a SQLException:

    public long executeUpdateActionStatement(String sqlStatement, int autoGeneratedKeys) {

    ResultSet rs = null;
    Statement stmt = null;
    int rowCount = 0;
    try {
        connect();
        stmt = connect.createStatement();

        rowCount = stmt.executeUpdate(sqlStatement, autoGeneratedKeys);


        // if no new row is inserted, later I do a select to get the key
        if (rowCount < 1) 
            return -1;

        stmt.getGeneratedKeys();    /* This step throws the exception ! */
        if (rs.next()) {
            long id = rs.getLong(1);
            System.out.println(" !! ==---> ID: " + id + " | : " + sqlStatement);
            return id;
        }


    } catch (SQLFeatureNotSupportedException feature) {
        feature.printStackTrace();
        System.out.println("|| ---->>> Fehler: SQLFeatureNotSupportedException: " + sqlStatement);

    } catch (SQLServerException sqlse) {
        sqlse.printStackTrace();
        System.out.println("|| ---->>> Fehler: SQLServerException: " + sqlStatement);
    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println("|| ---->>> Fehler: SQLException: " + sqlStatement);
    }

    finally {

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    return -1;

}

The SQLException I get:

    com.microsoft.sqlserver.jdbc.SQLServerException: Die Anweisung muss ausgeführt werden, bevor Ergebnisse abgerufen werden können.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getGeneratedKeys(SQLServerStatement.java:2040)

in english:

    The statement must be executed before any results can be obtained.

The SQL Statements:

    executeUpdateActionStatement("IF NOT EXISTS (SELECT GeoLocationId FROM GeoLocationCoordinates WHERE Longitude = " + longitude + 
    " AND Latitude = " + latitude + ") INSERT INTO GeoLocationCoordinates VALUES (" + longitude + ", " + latitude + ")", Statement.RETURN_GENERATED_KEYS); //Statement.RETURN_GENERATED_KEYS);

AND

    executeUpdateActionStatement("IF NOT EXISTS (SELECT PlaceId FROM Places WHERE TwitterPlaceId = \'" + p.getId() + "\') INSERT INTO Places VALUES (" + 
            placeData + ")", Statement.RETURN_GENERATED_KEYS);

The database-tables:

    /****** Object:  Table [dbo].[GeoLocationCoordinates]    Script Date: 16.08.2013 17:55:04 **************************************************************************/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE TABLE [dbo].[GeoLocationCoordinates](
        [GeoLocationId] [bigint] IDENTITY(1,1) NOT NULL,
        [Longitude] [float] NOT NULL,
        [Latitude] [float] NOT NULL, CONSTRAINT [PK_GeoLocationCoordinates] PRIMARY KEY CLUSTERED (  [GeoLocationId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

and

    /****** Object:  Table [dbo].[Places]    Script Date: 16.08.2013 17:57:16 **************************************************************************/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE TABLE [dbo].[Places](
      [PlaceId] [bigint] IDENTITY(1,1) NOT NULL,
      [TwitterPlaceId] [nvarchar](255) NULL,
      [PlaceName] [nvarchar](255) NULL,
      [PlaceFullName] [nvarchar](255) NULL,
      [StreetAdress] [nvarchar](255) NULL,
      [Country] [nvarchar](255) NULL,
      [PlaceType] [nvarchar](255) NULL,
      [PlaceUrl] [nvarchar](255) NULL,
      [BoundingBoxType] [nvarchar](255) NULL,
      [CountryTwoLetterCode] [nchar](2) NULL,
     CONSTRAINT [PK_Places] PRIMARY KEY CLUSTERED 
    (
  [PlaceId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO
1
  • Have you considered using a MERGE. That one will need a little tweaking but it is doing what you want (one or another action) but in an indivisible way. Sep 6, 2013 at 15:29

2 Answers 2

1

executeUpdate returns either 0, if no rows were affected, or the number of rows that were affected.

What step in your code is throwing the exception?

EDIT 2: Okay, looks like the merge will work.

PreparedStatement stmt = connection.prepareStatement(
        "merge table_1 t1 " +
        "using (select 'testvalue' as col1) t2 " +
        " on t1.col1 = t2.col1 " +
        " when not matched by target then " + 
        " insert (col1) values('testvalue'); "  
        ,Statement.RETURN_GENERATED_KEYS);

int out = stmt.executeUpdate();
System.out.println("Return:  " + out);  
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
    System.out.println("value:  " + rs.getLong(1));
}

If the value 'testvalue' doesn't exist in the destination table, it will be inserted. If it's inserted, the return value will be 1, and getGeneratedKeys will return the new row's identity column value. If it does exist, both methods will return 0.

8
  • Hi Andrew, this is the answer from the JavaDoc, that's right. But what does this mean to me if no row is inserted, because the row/the values exist in the table? Is the return value then 0? If a new row is inserted the return value should be 1. Sep 6, 2013 at 15:49
  • The step throwing the exception: stmt.getGeneratedKeys(); Sorry, I forgot to mark it! Sep 6, 2013 at 15:52
  • This is working for me: PreparedStatement stmt = connection.prepareStatement("yourinsertstatement,Statement.RETURN_GENERATED_KEYS), followed by: ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) {...
    – Andrew
    Sep 6, 2013 at 16:21
  • The only difference seems to be that you use a PreparedStatement instead of a Statement?! Are you using the stmt with a "IF NOT EXISTS (SELECT ...) INSERT INTO (...) Statement or "only" with a "simple" INSERT INTO (...) ?! Sep 6, 2013 at 16:30
  • Correct. If I use a Statement, I get the same error. If I use a PreparedStatement, it runs fine.
    – Andrew
    Sep 6, 2013 at 16:31
0

This is not syntactically correct, but gives an idea, just use scope identity in a transaction to get the new key and use it on child tables..The scrope in the transaction gives you hback the number you want. You'd just need to store the number of the found value in other code, if it exists. Could probably do it in the same proc, ideally.

declare @returnvalue int


BEGIN TRANSACTION
INSERT INTO GeoLocationCoordinates(longitude,latitude)
values (@lat,@long)

SELECT @returnvalue = SCOPE_IDENTITY()

INSERT INTO childtable (field1,field2,parentkey)
VALUES (@field1,@field2,@returnvalue)
COMMIT TRANSACTION
3
  • Thanks for your idea. Because of I insert many rows per second into the DB (with the help of a JAVA Listener), could it be possible that SCOPE_IDENTITY() delivers me not the identity-value of the INSERT of this transaction, but the identity-value of another transaction that runs/works "parallel" or when after this INSERT the INSERT of another transaction starts and then the SELECT @returnvalue = SCOPE_IDENTITY()-"Statement" is executed? Or is the/a transaction a "closed unit" for a DB and is executed completely before another SQL-Statement or a transaction is executed? Thanks! Sep 6, 2013 at 16:02
  • No, it should return the one value in the transaction. That's the purpose of wrapping it, in this case. Sep 6, 2013 at 16:07
  • This seems for me at a first glance to be the "cleanest" solution, perhaps in combination with the MERGE-"switch" (from above: @OldCurmudgeon commented) to decide if a new row has to be inserted or the values are already in the table. In the last case I have to SELECT the IDENTITY from the existing row, not the last inserted. Sep 6, 2013 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.