IDENT_CURRENT

How to use IDENT_CURRENT() is SQL. Is this function supported in MS Access. I am using JDBC-ODBC connectivity. I want to get generated Primary Key.

With DDL I rather mean the statement how you created the field.
So it is just a plain vanilla integer field? Not an identity field? Adding just a PK doesnt transform it automatically to an autogenerated identity field or so.
Refer to the SQL documentation of your database.

Similar Messages

  • Primary key violation when inserting records with insert_identity and ident_current+x

    My problem is this: I have data in a couple of temporary tables including
    relations (one table referencing records from another table by using
    temporary keys).
    Next, I would like to insert the data from the temp tables to my productive tables which have the same structure but their own identity keys. Hence, I need to translate the 'temporary' keys to regular identity keys in my productive tables.
    This is even more difficult because the system is highly concurrent, i.e. multiple sessions may try to insert
    data that way simultaneously.
    So far we were running the following solution, using a combination of
    identity_insert and ident_current:
    create table doc(id int identity primary key, number varchar(100))
    create table pos (id int identity primary key, docid int references doc(id), qty int)
    create table #doc(idx int, number varchar(100))
    create table #pos (docidx int, qty int)
    insert #doc select 1, 'D1'
    insert #doc select 2, 'D2'
    insert #pos select 1, 10
    insert #pos select 1, 12
    insert #pos select 2, 32
    insert #pos select 2, 9
    declare @docids table(ID int)
    set identity_insert doc on
    insert doc (id,number)
    output inserted.ID into @docids
    select ident_current('doc')+idx,number from #doc
    set identity_insert doc off
    -- Since scope_identity() is not reliable, we get the inserted identity values this way:
    declare @docID int = (select min(ID) from @docids)
    insert pos (docid,qty) select @docID+docidx-1, qty from #pos
    Since the request to ident_current() is located directly in the insert statement, we always have an implicit transaction which should be thread safe to a certain extend.
    We never had a problem with this solution for years until recently when we were running in occasional primary key violations. After some reasearch it turned out, that there were concurrent sessions trying to insert records in this way.
    Does anybody have an explanation for the primary key violations or an alternative solution for the problem?
    Thank you
    David

    >> My problem is this: I have data in a couple of temporary tables including relations (one table referencing records [sic] from another table by using temporary keys [sic]). <<
    NO, your problem is that you have no idea how RDBMS and SQL work. 
    1. Rows are not anything like records; this is a basic concept.
    2. Temp tables are how old magnetic tape file mimic scratch tapes. SQL programmers use CTEs, views, derived tables, etc. 
    3. Keys are a subset of attributes of an entity, fundamental characteristics of them! A key cannot be temporary by definition. 
    >> Next, I would like to insert the data from the temp tables to my production tables which have the same structure but their own IDENTITY keys. Hence, I need to translate the 'temporary' keys to regular IDENTITY keys in my productive tables. <<
    NO, you just get worse. IDENTITY is a 1970's Sybase/UNIX dialect, based on the sequential file structure used on 16-bit mini computers back then. It counts the physical insertion attempts (not even successes!) and has nothing to with a logical data model. This
    is a mag tape drive model of 1960's EDP, and not RDBMS.
    >> This is even more difficult because the system is highly concurrent, i.e. multiple sessions may try to insert data that way simultaneously. <<
    Gee, that is how magnetic tapes work, with queues. This is one of many reasons competent SQL programers do not use IDENTITY. 
    >> So far we were running the following solution, using a combination of IDENTITY_INSERT and IDENT_CURRENT: <<
    This is a kludge, not a solution. 
    There is no such thing as a generic “id” in RDBMS; it has to be “<something in particular>_id” to be valid. You have no idea what the ISO-11179 rules are. Even worse, your generic “id” changes names from table to table! By magic, it starts as a “Doc”,
    then becomes a “Pos” in the next table! Does it wind up as a “doc-id”? Can it become a automobile? A squid? Lady Gaga? 
    This is the first principle of any data model; it is based on the Law of Identity; remember that from Freshman Logic 101? A data element has one and only one name in a model. 
    And finally, you do not know the correct syntax for INSERT INTO, so you use the 1970's Sybase/UNIX dialect! The ANSI/ISO Standard uses a table consrtuctor: 
    INSERT INTO Doc VALUES (1, 'D1'), (2, 'D2'); 
    >> We never had a problem with this solution for years until recently when we were running in occasional PRIMARY KEY violations. After some research it turned out, that there were concurrent sessions trying to insert records [sic] in this way. <<
    “No matter how far you have gone down the wrong road, turn around.” -- Turkish proverb. 
    You have been mimicking a mag tape file system and have not written correct SQL. It has caught up with you in a way you can see. Throw out this garbage and do it right. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Ident_Current('TableName') not giving last inserted identity Value in SQL Server 2012

    Hi ,
    Ident_Current('TableName') is not giving last inserted identity Value in SQL Server 2012. 
    Latest Value of ID and Ident_Current is differing for that particular table.  
    Why its happening? Ident_Current value is greater than last inserted ID.
    Please guide me why its happening?

    Here is one example:
    CREATE DATABASE PMCtest ON (NAME = 'PMCtest', FILENAME = 'B:\ProdDB-Unzipped\PMCtest.mdf', SIZE = 25GB )
    LOG ON (NAME = 'PMCtest_log', FILENAME = 'B:\ProdDB-Unzipped\PMCtest.ldf', SIZE = 2GB)
    CREATE TABLE identity_crisis (a int IDENTITY NOT NULL PRIMARY KEY,
                                  b sysname NOT NULL CHECK (b <> 'sysschobjs'))
    go
    INSERT identity_crisis (b) VALUES ('First name')
    INSERT identity_crisis SELECT name FROM sys.objects
    go
    SELECT MAX(a), ident_current('identity_crisis')
    FROM  identity_crisis
    go
    DROP TABLE identity_crisis
    Because the second INSERT statement fails, the identity values from 2 to 12 are lost. This is a very intentional design to promote high concurrency. If you don't want gaps, you should not use IDENTITY, but roll your own.
    Also, beware that ident_current returns database-wide value, so if you insert one row, and another process inserts another row before you interrogate ident_current, you will get the id for the row of the other process.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Problem to store a oracle sql result into a variable

    Hello everyone,
    I'm working on a little project that use c#, Oracle ODT and asp.net, so here is the thing, I need to save the result of a sequence (SECNUM.NEXTVAL ) into a variable, then call that value from many inserts and querys and for last make the commit. My problem is that I don't know how to convert the string result to a number and the call it from the statements. Always brings two errors, one is invalid number because Im sending a string and the another is that if I comment the line cmd.ExecuteNonQuery(); the script runs but no commit happens.
    This is my code, is attached to a button:
    C# Syntax (Toggle Plain Text)
    string oradb = "Data Source=BBDD;User Id=DEMO;Password=DEMO;";
    string cmd1 = "SELECT SECNUM.NEXTVAL FROM DUAL";
    OracleConnection conn = new OracleConnection(oradb);
    conn.Open();
    OracleParameter parm = new OracleParameter();
    parm.OracleDbType = OracleDbType.Decimal;
    OracleCommand cmd = new OracleCommand();
    cmd.Connection = conn;
    cmd.Parameters.Add(parm);
    cmd.CommandText = "INSERT INTO DEMOINCI (CODINCI, CODCLI) VALUES (('" + cmd1 +"'), 'TEST')";
    cmd.CommandText = "INSERT INTO DEMOINCILIN (CODINCI,CODLIN) VALUES (('" + cmd1 +"'),1)";
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
    So my problem is that the column CODINCI is a column number of (9) and not a VARCHAR and can not be changed because is already have data, so when I use the code of the example, Oracle return an error saying Invalid number (of course).
    With the help of a friend I tried to put with the cast like this cmd.CommandText = "INSERT INTO DEMOINCI (CODINCI, CODCLI) VALUES (" + "CAST(" + cmd1 + "AS NUMBER), 'TEST')"; and it works but only if I comment the line cmd.ExecuteNonQuery();, so the commit never happend and of course there is no insert in the database.
    ¿It is so difficult to store a result of an SQL into a variable and then call it back on a statement?, on Oracle Forms you create a cursor like cursor=CVAL SELECT SECNUM.NEXTVAL VAL FROM DUAL and that it you can then use the VAL result into all other queries of the same form an retrieving with the :VAL option.
    Thanks for all the help.

    I just had to do something similar for my C# class, using SQL Server. The primary key for a "Customers" table was an auto-incrementing integer. After inserting a new customer I had to retrieve and display the primary key:
    string selectStatement = "SELECT IDENT_CURRENT('Customers') from Customers";
    SqlCommand selectCommand = new SqlCommand(selectStatement, connection);
    int customerID = Convert.ToInt32(selectCommand,ExecuteScalar());
    The ExecuteScalar() method of selectCommand returned the first column of the first row of the dataset, which in this case was the key of the new Customers record, as an object. Convert.ToInt32() converted the key to an integer.
    Once you store SECNUM.NEXTVAL as an integer, you can use it to create a Parameter for the Command object.
    HTH.

  • How to find out who made inserts/updates/deletes made to a SQL Table

    I want to know WHO MAKES INSERTS/UPDATES/DELETES TO a particular SQL Table. Bascially I want to AUDIT ANY Edites made to a SQL 2008 TABLE. I need info such as WHO AMDE THE Updates i.e. the user first/lastname, When update was made, what row was updated etc...How
    can I do that with SQL 2008?

    One way to achieve that would be to use triggers to detect when a change is made to the table, and then insert a record into another table/database detailing what changed and who by.
    You'd need three triggers, one for insert, update and delete respectively, and for each of those you use the "inserted" and "deleted" tables (system tables maintained by SQL) to retrieve what has been done. To retrieve who made the change you can query IDENT_CURRENT
    which returns the last identity value for a specific table.
    See :
    Triggers -
    http://msdn.microsoft.com/en-gb/library/ms189799(v=sql.100).aspx
    Inserted & deleted tables -
    http://technet.microsoft.com/en-us/library/ms191300(v=sql.100).aspx
    INDENT_CURRENT -
    http://technet.microsoft.com/en-us/library/ms175098(v=sql.100).aspx
    There may be better / more up to date ways to do this, but I've used this method successfully in the past, albeit a long time ago (on a SQL 2000 box I think!).

  • Mass Creation of Variants

    I have hundreds of products that all have the same variant configurations, and I understandably don't want to pay someone to manually go through the WebTools interface to create all the variants.  After looking through the WebTools database, I am planning on creating a little SQL script that will copy the variant information from one product to another. 
    1)  Select all records from Variant table where ConfigPartNo = 'itemtocopyfrom'
    2)  Create new rows in Variant table that match the previously selected rows, switching out the ConfigPartNo to 'itemtocopyto'
    3)  For each of the first selected VariantIDs in the Variant table, Select all the records in the PartsVariant table where VariantID = VariantID
    4)  Duplicate each of those rows, substituting the new VariantID of the parts created in step 2
    I can't find anyplace else that is affected by the creation of variants.  Will this work, or is there a better way to approach this?
    Thanks,
    Derek

    In case anybody else is interested, I whipped up this in Access VBA today.  Basically all the form does is have two list boxes filled with all the products in WebTools.  You can only select one from the FROM listbox, but you can select as many products in the TO listbox as you want.  This code then loops through all of the selected TO products, duplicating all the variants settings of the FROM column. 
    My code is only lightly commented and does very little error checking, but it does the job.  One thing to note if you end up using this code is that it doesn't check to see if it is duplicating variants, so if you click it twice or run it on a product that already has variants, it will add all of the variants from the FROM product.
    Depending on how much I need to use this, I may extend it a little more so that I can choose to copy only certain variant categories rather than all variant categories, but we'll see.  If I do anything significant, I'll hopefully remember to come post it here.
    If anyone is interested in the original Access database that runs this, just send me an email at derek AT seatability DOT com and I'll send it over to you.
    Dim SQL As String
    Dim con As ADODB.Connection
    Dim rsVariantFrom As ADODB.Recordset
    Dim rsVariantTo As ADODB.Recordset
    Dim rsPartsVariantFrom As ADODB.Recordset
    Dim rsPartsVariantTo As ADODB.Recordset
    Dim rsAutoVariantID As ADODB.Recordset
    Dim rsPartsMaster As ADODB.Recordset
    Dim CopyFromProductID As String
    Dim CopyToProductID As String
    Dim AutoVariantID As Integer
    Dim varItm As Variant
        CopyFromProductID = lstCopyFromPartNo.Value
        'Open Database Connection
        Set con = New ADODB.Connection
        con.ConnectionString = "Driver={SQL Server};" & _
                   "Server=server;" & _
                   "Database=database;" & _
                   "Trusted_Connection=yes"
        con.Open
        For Each varItm In lstCopyToPartNo.ItemsSelected
            CopyToProductID = lstCopyToPartNo.ItemData(varItm)
            Set rsVariantFrom = New ADODB.Recordset
            SQL = "SELECT * FROM Variant WHERE ConfigPartNo = '" & CopyFromProductID & "'"
            rsVariantFrom.Open SQL, con, adOpenForwardOnly, adLockReadOnly
            Set rsVariantTo = New ADODB.Recordset
            SQL = "SELECT * FROM Variant WHERE ConfigPartNo = '0'"
            rsVariantTo.Open SQL, con, adOpenDynamic, adLockOptimistic
            Do Until rsVariantFrom.EOF
                ' Copy all the old Variant Fields, only changing the ConfigPartNo to the new ProductID
                rsVariantTo.AddNew
                    rsVariantTo.Fields("ConfigPartNo").Value = CopyToProductID
                    rsVariantTo.Fields("Description").Value = rsVariantFrom.Fields("Description").Value
                    rsVariantTo.Fields("ImageURL").Value = rsVariantFrom.Fields("ImageURL").Value
                    rsVariantTo.Fields("MarketingText").Value = rsVariantFrom.Fields("MarketingText").Value
                    rsVariantTo.Fields("VariantType").Value = rsVariantFrom.Fields("VariantType").Value
                    rsVariantTo.Fields("DefaultPartNo").Value = rsVariantFrom.Fields("DefaultPartNo").Value
                    rsVariantTo.Fields("RequiredFlag").Value = rsVariantFrom.Fields("RequiredFlag").Value
                    rsVariantTo.Fields("SortOrder").Value = rsVariantFrom.Fields("SortOrder").Value
                    rsVariantTo.Fields("SynchFlag").Value = rsVariantFrom.Fields("SynchFlag").Value
                    rsVariantTo.Fields("SynchDate").Value = rsVariantFrom.Fields("SynchDate").Value
                rsVariantTo.Update
                ' Retrieve most recent Autoincrement / Identity value from connection
                Set rsAutoVariantID = New ADODB.Recordset
                SQL = "SELECT IDENT_CURRENT('Variant')"
                rsAutoVariantID.CursorLocation = adUseServer
                rsAutoVariantID.Open SQL, con, adOpenForwardOnly, adLockReadOnly, adCmdText
                AutoVariantID = rsAutoVariantID.Fields(0).Value
                rsAutoVariantID.Close
                Set rsAutoVariantID = Nothing
                Set rsPartsVariantFrom = New ADODB.Recordset
                SQL = "SELECT * FROM PartsVariant WHERE VariantID = '" & rsVariantFrom.Fields("VariantID").Value & "'"
                rsPartsVariantFrom.Open SQL, con, adOpenForwardOnly, adLockReadOnly
                'Return an empty recordset to add the copied PartsVariant rows
                Set rsPartsVariantTo = New ADODB.Recordset
                SQL = "SELECT * FROM PartsVariant WHERE VariantID = '0'"
                rsPartsVariantTo.Open SQL, con, adOpenDynamic, adLockOptimistic
                ' Copy all the old PartsVariant fields, only changing the VariantID to the new VariantID
                Do Until rsPartsVariantFrom.EOF
                    rsPartsVariantTo.AddNew
                       rsPartsVariantTo.Fields("VariantID").Value = AutoVariantID
                       rsPartsVariantTo.Fields("PartNo").Value = rsPartsVariantFrom.Fields("PartNo").Value
                       rsPartsVariantTo.Fields("DisplayText").Value = rsPartsVariantFrom.Fields("DisplayText").Value
                       rsPartsVariantTo.Fields("UseBaseFlag").Value = rsPartsVariantFrom.Fields("UseBaseFlag").Value
                       rsPartsVariantTo.Fields("BaseAdj").Value = rsPartsVariantFrom.Fields("BaseAdj").Value
                       rsPartsVariantTo.Fields("SortOrder").Value = rsPartsVariantFrom.Fields("SortOrder").Value
                       rsPartsVariantTo.Fields("SynchFlag").Value = rsPartsVariantFrom.Fields("SynchFlag").Value
                       rsPartsVariantTo.Fields("SynchDate").Value = rsPartsVariantFrom.Fields("SynchDate").Value
                    rsPartsVariantTo.Update
                    rsPartsVariantFrom.MoveNext
                Loop
                ' Close PartsVariant recordsets and destroy object
                rsPartsVariantFrom.Close
                rsPartsVariantTo.Close
                Set rsPartsVariantFrom = Nothing
                Set rsPartsVariantTo = Nothing
                rsVariantFrom.MoveNext
            Loop
            ' Set the master record of the item to be a Variant Master
            Set rsPartsMaster = New ADODB.Recordset
            SQL = "UPDATE PartsMaster " & _
                    "SET VariantMasterFlag = 'Y' " & _
                    "WHERE PartNo = '" & CopyToProductID & "'"
            rsPartsMaster.Open SQL, con
            ' Close Variant recordsets and destroy object
            rsVariantFrom.Close
            rsVariantTo.Close
            Set rsVariantFrom = Nothing
            Set rsVariantTo = Nothing
            Set rsPartsMaster = Nothing
        Next varItm
        con.Close
        Set con = Nothing

  • Automatic key assignment not working....

    Hi,
      The automatic key assignment is trying to assign a null value to the primary key(AccountID) on saving the record causing an error. Line is bold.
    Regards, Bob
    CREATE TABLE [dbo].[AppGlobal](
    [AccountID] [int] Identity (1,1) NOT NULL,
    [AppID] [varchar](50) NOT NULL,
    [AppPassword] [varchar](50) NOT NULL,
    [AppNickName] [varchar](50) NOT NULL,
    [AppCreateDate] [datetime] NOT NULL
    ) ON [PRIMARY]
    Public Shared Function AddLogin(thisADB As AppDB, ByRef AuditHdr As auditHdr) As List(Of AuditLineItem)
    Dim LineItemList As New List(Of AuditLineItem)
    Dim LineItemSeq As Integer = 0
    Dim connection As SqlConnection = BTDB.GetConnection
    Dim insertStatement As String =
    "INSERT AppGlobal " &
    "(AppID, AppPassword, AppNickName, AppCreateDate) " &
    "VALUES (@AppID, @AppPassword, @AppNickName, @AppCreateDate)"
    Dim insertCommand As New SqlCommand(insertStatement, connection)
    AuditHdr = New auditHdr
    'AuditHdr.AuditID = 0
    AuditHdr.AccountID = 999999
    'Dim auditHdr As auditHdr
    AuditHdr.CreateDate = Now
    AuditHdr.TableName = "AppGlobal"
    AuditHdr.Action = "A"
    AuditHdr.ScreenID = gm_ScrID
    Dim auditLineItem As AuditLineItem
    insertCommand.Parameters.AddWithValue("@AppID", thisADB.AppID)
    auditLineItem = New AuditLineItem
    auditLineItem.AuditID = AuditHdr.AuditID
    LineItemSeq = LineItemSeq + 1
    auditLineItem.AuditSequence = LineItemSeq
    auditLineItem.FieldName = "E-mail"
    auditLineItem.BeforeValue = ""
    auditLineItem.AfterValue = thisADB.AppID
    LineItemList.Add(auditLineItem)
    insertCommand.Parameters.AddWithValue("@AppPassword", thisADB.AppPassword)
    auditLineItem = New AuditLineItem
    auditLineItem.AuditID = AuditHdr.AuditID
    LineItemSeq = LineItemSeq + 1
    auditLineItem.AuditSequence = LineItemSeq
    auditLineItem.FieldName = "Password"
    auditLineItem.BeforeValue = ""
    auditLineItem.AfterValue = thisADB.AppPassword
    LineItemList.Add(auditLineItem)
    insertCommand.Parameters.AddWithValue("@AppNickName", thisADB.AppNickName)
    auditLineItem = New AuditLineItem
    auditLineItem.AuditID = AuditHdr.AuditID
    LineItemSeq = LineItemSeq + 1
    auditLineItem.AuditSequence = LineItemSeq
    auditLineItem.FieldName = "NickName"
    auditLineItem.BeforeValue = ""
    auditLineItem.AfterValue = thisADB.AppNickName
    LineItemList.Add(auditLineItem)
    insertCommand.Parameters.AddWithValue("@AppCreateDate", thisADB.AppCreateDate)
    auditLineItem = New AuditLineItem
    auditLineItem.AuditID = AuditHdr.AuditID
    LineItemSeq = LineItemSeq + 1
    auditLineItem.AuditSequence = LineItemSeq
    auditLineItem.FieldName = "CreateDate"
    auditLineItem.BeforeValue = ""
    auditLineItem.AfterValue = CStr(thisADB.AppCreateDate)
    LineItemList.Add(auditLineItem)
    Try
    connection.Open()
    Dim insertCount As Integer = insertCommand.ExecuteNonQuery
    Dim selectStatement As String =
    "SELECT IDENT_CURRENT('AppGlobal') FROM AppGlobal"
    Dim selectCommand As New SqlCommand(selectStatement, connection)
    Dim AccountID As Integer = CInt(selectCommand.ExecuteScalar)
    gm_AccountID = AccountID
    If insertCount < 1 Then
    LineItemList = Nothing
    End If
    Catch ex As SqlException
    MessageBox.Show("SQL Server error #4 " & ex.Number & ": " & ex.Message, ex.GetType.ToString)
    Finally
    connection.Close()
    End Try
    Return LineItemList
    End Function

    See how to retrieve identity value through .net here
    http://www.aspsnippets.com/Articles/Return-Identity-Auto-Increment-Column-value-after-record-insert-in-SQL-Server-Database-using-ADONet-with-C-and-VBNet.aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Cloning the GeneratedValue for another column during insert

    I have an entity for a MSSQL table with IDENTITY auto-generated primary key column. I want another column (int as well) to have the same value set during an insert.
    How can I do this using JPA? It's my understanding that the @Id and @GeneratedValue(strategy=GenerationType.IDENTITY) annotations can only be assigned to a single getter method.
    I tried using entityManager.createNativeQuery("SELECT IDENT_CURRENT('fooTable')").getResultList();but that doesn't return a resultset. Same problem if I use JDBC.

    This a Seam app and I'm using Hibernate manual flush. So alternatively I could do an insert using persist() then flush() then update using merge() then flush() all in one method (one transaction using CMT).

  • Bug in auto-increment for MSSQL

    I am using kodo 3.1.0 and have a scenario where I am persisting a new object
    that uses an auto-increment PK and the database has an on-insert trigger
    that inserts a log into an audit table.
    At the database level, what is happing is:
    1) kodo calls "insert into t_timeentry (........)
    2) the database calls "insert into t_timeentrylog (......)
    3) kodo calls @@IDENTITY to get the ID to associate with the new timeentry.
    The problem is, @@IDENTITY is getting back the last identity used,
    regardless of table, so it is returning the id inserted into t_timeentrylog
    and kodo thinks that's the id of the timeentry. In the end, I get a
    optimistic lock exception when I try to update the new timeentry because it
    is trying to update based on the id of the timeentrylog.
    What you need to do is call SCOPE_IDENTITY or IDENT_CURRENT rather than
    @@IDENTITY when you get auto-incremented columns. Unfortunately, those
    functions only exist in SQL 2000 (maybe 7), so people with SQL6.5 (and maybe
    7) are just out luck if they have triggers on inserts.
    Is there a work-around for this? It's causing problems throughout my
    system.
    Nathan

    If the query string you want executed to get the last auto-inc value
    does not rely on context, you can set it easily with:
    kodo.jdbc.DBDictionary: LastGeneratedKeyQuery="<sql>"
    If it is more complex, then you'll need to extend
    kodo.jdbc.sql.SQLServerDictionary and override the following method:
    public long getGeneratedKey (kodo.jdbc.schema.Column col,
    Connection conn)
    throws SQLException
    // if you need the col or table name:
    String colName = col.getName ();
    String tableName = col.getTable ().getName ();
    // execute the necessary SQL to return the last inserted value...
    Then you can plug your dictionary into Kodo with:
    kodo.jdbc.DBDictionary: your.custom.Dictionary

  • How to use sequence in MS sql server?

    In Oracle DB we use sequence like that:
    SequenceImpl s = new SequenceImpl("customer_seq", getDBTransaction());
    Integer next = (Integer)s.getData();
    setId(new Number(next.intValue()));
    But there is no sequence in sql server ,how can I do?
    Thank you~~

    MS SQLServer have a IDENTITY column property and UNIQUEIDENTIFIER data type that is somewhat similar to Oracle's sequence. I don't know whether your table contain either of these, or you just want to set sequential number to a column.
    Below is some info about IDENTITY and UNIQUEIDENTIFIER you may already know since they are in SQLServer Book.
    IDENTITY property: You can define IDENTITY property on a numeric column. You can set the seed and increment on this column property very much like Oracle's sequence. The only thing I think it does not have is the "nextval". You can use IDENT_CURRENT function or @@IDENTITY after an INSERT or SELECT INTO to get the last value generated. Of course you can use this value and add the increment to get the next
    value but it not the same as seqname.nextval which keep incrementing each time you call it. Getting the current identity value and adding the increment your self will not work for multiple sessions with pending
    insert. Another thing about column with IDENTITY property is that you cannot insert value into this column (i.e, omit it in your insert statement values) unless IDENTITY_INSERT is on, but only one table in a
    session can have IDENTITY_INSERT to be turned on.
    If you don't need to know the next seq value, then IDENTITY work similar to Oracle sequence. Execute select after postchanges or commit will have system generated values. If you need to get next value before insert, Sung suggest using SEQ_TABLE and managing the next value (write a database function to mimic Oracle'
    s nextval).
    UNIQUEIDENTIFIER datatype: UNIQUEIDENTIFIER is a 16-byte hexadecimal number indicating a globally unique identifier (GUID). The GUID is useful when a row must be unique among many other rows. You could use NEWID() to create a value of type uniqueidentifier or calling some API function that returns a GUID. The advantage of using uniqueidentifier is that the values generated by NEWID function or application GUID are guaranteed to be unique throughout the world. The disadvantage of using uniqueidetifier is that it is long and obscure, random, difficult for user to remember or type correctly. It is 16 byte, which is large compare to other datatype such as 4-byte integer.
    Thanks,
    Yvonne

  • Return results from ADEP in AS3 Arrays, not ArrayCollections

    Hi all,
    Is there any way to force ADEP to return results from data services in simple AS3 Arrays, not ArrayCollections? Here are my situation:
    In my project I use ADEP Data Management Services. To connect to ADEP services we use RTMP channel defined in services-config.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <services-config>
         <services>
              <service-include file-path="remoting-config.xml" />
              <service-include file-path="proxy-config.xml" />
              <service-include file-path="messaging-config.xml" />
              <service-include file-path="data-management-config.xml" />
              <service-include file-path="managed-remoting-config.xml" />
              <service class="fiber.data.services.ModelDeploymentService" id="model-deploy-service" />
              <default-channels>
                   <channel ref="my-rtmp"/>
              </default-channels>
         </services>
         <channel-definition id="my-rtmp" class="mx.messaging.channels.RTMPChannel">
              <endpoint url="rtmp://{server.name}:1000" class="flex.messaging.endpoints.RTMPEndpoint"/>
              <properties>
                   <idle-timeout-minutes>20</idle-timeout-minutes>
                   <block-rtmpt-polling-clients>true</block-rtmpt-polling-clients>
                   <rtmpt-poll-wait-millis-on-client>0</rtmpt-poll-wait-millis-on-client>
              </properties>
         </channel-definition>
    </services-config>
    To manage data in database we defined data services in data-management-config.xml like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <service id="data-service" class="flex.data.DataService">
        <adapters>
            <adapter-definition id="java-dao" class="flex.data.adapters.JavaAdapter"/>
            <adapter-definition id="mr-java-dao" class="flex.data.adapters.ManagedRemotingDataAdapter" />
            <adapter-definition id="actionscript" class="flex.data.adapters.ASObjectAdapter" default="true"/>
        </adapters>
        <default-channels>
            <channel ref="my-rtmp"/>
        </default-channels>
        <destination id="SomeProduct.SomeItems">
            <adapter ref="java-dao" />
            <properties>
                <source>flex.data.assemblers.SQLAssembler</source>
                <scope>application</scope>
                <metadata>
                    <identity property="ID" />
                </metadata>
                <server>
                    <database>
                        <datasource>java:comp/env/jdbc/SP</datasource>
                    </database>
                    <actionscript-class>com.somecompany.classes.SomeCoolClass</actionscript-class>
                    <create-item>
                        <procedure name="SomeItems_Insert">
                            <procedure-param property-value="#Session_ID#" />
                            <procedure-param property-value="#Division_ID#" />
                            <procedure-param property-value="#Salesrep_ID#" />
                            <procedure-param property-value="#Area_Code#" />
                            <procedure-param property-value="#Item_ID#" />
                        </procedure>
                        <id-query>SELECT IDENT_CURRENT('Work_Area_Item')</id-query>
                    </create-item>
                    <fill>
                        <name>all</name>
                        <procedure name="SomeItems_Get">
                            <procedure-param property-value="#Session_ID#" />
                            <procedure-param property-value="#Last_Sync_Time#" />
                        </procedure>
                    </fill>
                    <update-item>
                        <procedure name="SomeItems_Update">
                            <procedure-param property-value="#Session_ID#" />
                            <procedure-param property-value="#Division_ID#" />
                            <procedure-param property-value="#Salesrep_ID#" />
                            <procedure-param property-value="#Area_Code#" />
                            <procedure-param property-value="#Item_ID#" />
                       </procedure>
                    </update-item>
                    <delete-item>
                        <procedure name="SomeItems_Delete">
                            <procedure-param property-value="#Session_ID#" />
                            <procedure-param property-value="#Item_ID#" />
                        </procedure>
                    </delete-item>
                </server>
            </properties>
        </destination>
    </service>
    By default, ADEP returns results from SomeProduct.SomeItems destination to Flex side as ArrayCollection of SomeCoolClass instances but I need the data to be returned in simple AS3 Arrays. Recently, I found that there is small optional serialization configuration in channel-definition that should resolve my problem. So I updated my channel-definition in services-config.xml to this:
    <channel-definition id="my-rtmp" class="mx.messaging.channels.RTMPChannel">
         <endpoint url="rtmp://{server.name}:1000" class="flex.messaging.endpoints.RTMPEndpoint"/>
         <properties>
              <serialization>
                   <legacy-collection>true</legacy-collection>
              </serialization>
              <idle-timeout-minutes>20</idle-timeout-minutes>
              <block-rtmpt-polling-clients>true</block-rtmpt-polling-clients>
              <rtmpt-poll-wait-millis-on-client>0</rtmpt-poll-wait-millis-on-client>
         </properties>
    </channel-definition>
    However, result are still returned in ArrayCollections.
    Any ideas?
    Thanks in advance

    Thom Parker answered this here: http://forums.adobe.com/message/2614570#2614570
    Answer copied below:
    "The problem is that when the focus is on the text box
    it's in edit mode. It's only displaying the value interactively entered by
    the user, or as a consequence of the change event.  What you need to do is
    force the focus off of the text box in code.  You can do a little trick
    where you bounce it to a tiny transparent field, which then bounds the focus
    back so it doesn't look like the focus changed."
    What I ended up doing was calling up the dialog box, then using setfocus with no parameters to remove focus from the field, as follows:
    this.rawValue = this.dialogBoxFunction(this.rawValue); // passing current value so dialog box defaults to that value
    xfa.host.setFocus();
    Cheers,
    Marty.

  • Gets the new id of auto-increment field by jdbc

    There is a auto-increment index field of a table. I would like to add a row in that table by jdbc. The process is success and the index will increase automatically. However i would like to get the newly added index number. How can i do this? Thanks a lot.

    This is off of Microsoft's T-SQL site http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_tsqlcon_6lyk.asp
    @@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.
    IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.

  • Content Server Analyzer FAILS

    Folks,
    I wanted to run the Content Server Analyzer (11g/SQL Server 2008) to check the file system for integrity, and when I try to do that I get the following error:
    "Unable to create the result set for query 'QnativeCurrentCounter (SELECT IDENT_CURRENT(idcSeqRevID) as dCurrentIndex)'. [FMWGEN][SQLSErver JDBC Driver][SQLServer] Invalid column Name 'IdcSeqRevId'"
    I tried a couple of different options (like checking the database, etc.) and they ALL fail with the same error.
    Again, UCM 11g and SQL Server 2008. Nothing is in the idcAnalyzer.log file except "Analyzing Filesystem..." or "Analyzing tables..." -- nothing else.
    Any ideas here? We are seeing some issues on our PROD server that files are missing (when trying to archive out), so I really need to run the analysis....
    Thanks!

    Just to answer my own question in case anyone else runs into the issue:
    The answer to this is that there is a bug in UCM 11.1.1.5.
    In the C:\Oracle\Middleware\Oracle_ECM1\ucm\idc\resources\core\tables\query.htm file, the select is WRONG.
    IT is by default:
    <tr>
         <td>(MSSQLSERVER)QnativeCurrentCounter</td>
         <td>SELECT IDENT_CURRENT(?) AS dCurrentIndex</td>
         <td>dNativeCounterName table</td>
    </tr>
    The Fix is to change that to:
    <tr>
         <td>(MSSQLSERVER)QnativeCurrentCounter</td>
         <td>SELECT IDENT_CURRENT*('?')* AS dCurrentIndex</td>
         <td>dNativeCounterName table</td>
    </tr>

  • IDENTITY_INSERT Error

    We have recently migrated to Coldfusion 8 and have found that certain ALTER SQL commands that ran just fine in our old Coldfusion 7 environment will generate errors in CF8. We verified that all permission are given in both Coldfusion 8 Administrator Datasource Settings and SQLServer 2005 for ALTER rights to this table but we continue to get the following error.
    [Macromedia][SQLServer JDBC Driver][SQLServer]Cannot find the object "dbo.SCI_Group" because it does not exist or you do not have permissions.
    Here is our SQL Query that we are executing:
          DECLARE @base INT
          DECLARE @fyr INT
          SET @base = IDENT_CURRENT('dbo.SCI_Group')
          SET @fyr = 2009
          SET IDENTITY_INSERT dbo.SCI_Group ON
          INSERT INTO SCI_Group
            (ID, ParID, OldID, DowID, FYR, Name, Sort, Description, f_Input, f_Output, f_Enabled, f_Parent)
            SELECT
            ID + @base,
            ParID + @base,
            ID,
            DowID,
            @fyr,
            Name,
            Sort,
            Description,
            f_Input,
            f_Output,
            f_Enabled,
            f_Parent
          FROM
            SCI_Group
          WHERE
            FYR = (@fyr - 1)
          SET IDENTITY_INSERT dbo.SCI_Group OFF
    Any insight from prior experience on this error type is much appreciated.
    Thanks!
    Mike

    Things to check:
    1. Does the code execute correctly without SET IDENTITY_INSERT statements?
    2. Check permissions for your login.  From the Microsoft documentation for SET IDENTITY_INSERT: "User must own the object, or be a member of the sysadmin fixed server role, or the db_owner and db_ddladmin fixed database roles."
    http://msdn.microsoft.com/en-us/library/ms188059(SQL.90).aspx
    From the Microsoft documentation for IDENT_CURRENT: "Returns NULL on error or if a caller does not have permission to view the object. In SQL Server 2005, a user can only view the metadata of securables that the user owns or on which the user has been granted permission. This means that metadata-emitting, built-in functions such as IDENT_CURRENT may return NULL if the user does not have any permission on the object. For more information, see Metadata Visibility Configuration and Troubleshooting Metadata Visibility."
    http://msdn.microsoft.com/en-us/library/ms175098(SQL.90).aspx
    3. Can you wrap your SQL into a stored procedure and using that instead of using a batch of SQL statements?
    Were there any database, network, or ColdFusion changes in the upgrade other then the move from CF7 to CF8?

  • Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. This failure occured while attempting to connect to the Principle server.

    We are using SQL Server 2012.
    Every now and then, when we execute the below stored procedure INSERT_INTO_MYTBL, we got the below error, and it returned @ID = 0.
    "Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding. 
    This failure occured while attempting to connect to the Principle server."
    What causes this error, and how can we fix it ?
    Thank you.
    create procedure INSERT_INTO_MYTBL
    @ID int output,
    @Order varchar(50) = NULL,
    @ACCOUNT varchar(20) = NULL
    AS
    DECLARE @Success int, @TryNr int, @ErrMsg varchar(500), @ErrNumber int, @expected_id int;
    SET @Success = 0;
    SET @TryNr = 1;
    SET @ErrMsg = ''
    WHILE @Success = 0 AND @TryNr <= 3 and @ErrMsg = ''
    BEGIN;
    BEGIN TRY;
    BEGIN TRANSACTION;
    retry:
    BEGIN TRY;
    SELECT @expected_id = ident_current('myTbl') + 1
    SELECT @order = @account + '-' + CAST(@expected_id AS varchar(50))
    insert into myTbl
    ([Order],ACCOUNT)
    values
    (@Order,@ACCOUNT)
    END TRY
    BEGIN CATCH;
    SELECT @ErrNumber = ERROR_NUMBER()
    IF @ErrNumber = 2627
    BEGIN;
    GOTO retry
    END;
    ELSE
    BEGIN;
    SET @ErrMsg = '1.' + ERROR_MESSAGE() + ' ' + @order
    RAISERROR (@ErrMsg, 16, 1);
    END;
    END CATCH
    select @ID = SCOPE_IDENTITY()
    IF @id <> @expected_id
    BEGIN
    UPDATE myTbl
    SET [Order] = @ACCOUNT + '-' + CAST(@ID AS varchar(50))
    WHERE ID = @ID
    END
    SET @Success = 1
    COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH;
    ROLLBACK TRANSACTION;
    SELECT @ErrNumber = ERROR_NUMBER()
    IF @ErrNumber = 1205
    BEGIN;
    SET @TryNr = @TryNr + 1;
    IF @TryNr > 3
    RAISERROR ('Giving up after 3 consecutive deadlocks for %s', 16, 1,@ACCOUNT);
    END;
    ELSE
    BEGIN;
    SET @ErrMsg = '2.' + ERROR_MESSAGE() + ' ' + @order
    RAISERROR (@ErrMsg, 16, 1);
    END;
    END CATCH;
    END;

    When the problem occurs, the stored procedure returns @ID = 0, which I think means the query
    When the problem occurs, the procedure does not return anything. SQL Server was told to stop executing. Furthermore, unless you issue the command SET XACT_ABORT ON, SQL Server will not roll back any open transaction. Which is one more reason you should not
    permit command timeouts.
    As for why this procedure sometimes take a long time, I would primarily suspect locking. When this occurs (but before the timeout elapses!), you could use my beta_lockinfo to see if there is any blocking going on. You find it here:
    http://www.sommarskog.se/sqlutil/beta_lockinfo.html
    Erland Sommarskog, SQL Server MVP, [email protected]

Maybe you are looking for

  • Setup problem - sql server 2014 - "could not find the database engine startup handle" - 0x851a0019

    I tried to install ,deleted and re-installed several times and no help at all. visual studio 2013 with update 2 rc and adk installed in my computer. error code: 0x851a0019 error messege in setup: could not find the database engine startup handle edit

  • Unusual behavior in planning book at the time of saving data

    Hi Experts, I am having a problem that in the planning book when I try to save the data accordingly:- a) Enter the data and then press save button and then click the save button:- In this case the data is getting saved. b) Enter the data and then wit

  • Firefox 4 is hard to read, the fonts are fuzzy as in IE 9

    Hi, with Firefox 4 the fonts are now the same as in Internet Explorer 9 : it is unclear, mostly in nonserif fonts. Is there a way I can disable that strange new feature?

  • Avchd render time: 1 min = 1 hour of rendering.

    so should 1 min of 1920 x 1080 avchd footage  take about an hour to render? I know I don't have a high end machine but that cant be right. footage is  l layer of avchd footage with simple dissolves. no other special FX. I have tried neosceen Avis and

  • Using the Result of an Insert

    I'm using an Informatica Cloud mapping to do an insert of a contact into NetSuite based on an outbound message from Salesforce. That's working fine. What I need to do, though, is to somehow get the ID of the inserted contact in NetSuite so that I can