Return Auto Generated Key In Sql Server
- Return Auto Generated Key In Sql Server 2016
- Return Auto Generated Key In Sql Server Download
- Return Auto Generated Key In Sql Server Windows 7
- Return Auto Generated Key In Sql Server Free
By Jeff Smith on 24 April 2007 Tags: Table Design , Identity
Retrieving auto-generated keys for an INSERT statement With the IBM® Data Server Driver for JDBC and SQLJ, you can use JDBC 3.0 methods to retrieve the keys that are automatically generated when you execute an INSERT statement. Apr 08, 2016 SQL Primary key Auto Increment VB C# apps Don't forget to share and subscribe to my channel to get more contents how to create hotel manage sofware https://w.
These values are generated by the server as rows are added to a table. In SQL Server, you set the identity property of a column, in Oracle you create a Sequence, and in Microsoft Access you create an AutoNumber column. A DataColumn can also be used to generate automatically incrementing values by setting the AutoIncrement property to true. Learn how to define an auto increment primary key in SQL Server. This data tutorial will explain basic table creation and information around using identity a. The main value of this feature is to provide a way to make IDENTITY values available to an application that is updating a database table without a requiring a query and a second round-trip to the server. Because SQL Server doesn't support pseudo columns for identifiers, updates that have to use the auto-generated key feature must operate. Statement.executeUpdate(sql-statement, Statement.RETURNGENERATEDKEYS); The following forms are valid only if the data source supports SELECT FROM INSERT statements. Sql-statement can be a single-row INSERT statement or a multiple-row INSERT statement. With the first form, you specify the names of the columns for which you want automatically.
This article by Jeff Smith covers different ways to create sequence numbers. It starts with the basic identity and GUIDs and quickly moves to much more complicated sequence numbers including those with auto-incrementing mixed letters and numbers such as 'A0001', etc. Jeff shows one of the easiest ways I've ever seen to efficiently handle very odd sequence numbers.
Introduction
Sometimes you'd like the SQL Server itself to automatically generate a sequence for entities in your table as they are created. For example, assigning each new Customer added to your table a unique 'CustomerNumber'. There are effectively two ways to do using the built-in features that T-SQL provides:
- IdentityColumns - An identity is a common 'auto generated' primary key to use in a SQL Server database these days. An identity is simply an integer value that 'auto increments' as each new row is added to your table. You can specify when it should start and how it should increment when you add the column to your table:
- GUID Columns - A 'GUID' is a Globally Unique Identifier that can be assigned a unique yet random long string of characters like 'B3FA6F0A-523F-4931-B3F8-0CF41E2A48EE'. You can either use the NEWID() function when inserting into your table or set a default like this to implement a GUID column in your tables:
However, we often see questions in the forums regarding how to create other types of auto-generated sequences in tables. For example, you might want your customers to automatically be assigned 'Customer Numbers' as formatted like this:
In other cases, people would like to use incrementing letters instead of numbers, some combination of both, or for the digits to be 'reset' on some specific condition, and so on.
Windows 7 pro key generator app. The most important and crucial part of implementing this is not writing the code! It is clearly defining your specification and ensuring that it is logical and works for you. Before you can write code that will automatically generate sequences for you, you must consider:
- How many numbers will you ever need? Does your specification handle this?
- What happens when values are deleted? Are they re-used?
- Are these sequences dependant on data that might ever change? What happens to these values when the data does change? Does it make sense, then, to incorporate this data into your sequence algorithm?
- If you have a complicated rule (i.e., 'AA-00' through 'ZZ-99'), is every step and possibility clearly defined? In this example, what comes after AA-99? Is it 'BA-00', 'AB-00', 'BB-00', or something else? What comes after 'ZZ-99'?
So, the very first step is to clearly, accurately, and completely define how your sequence values will be generated. You must explicitly map out how to handle all possible situations and you must do some research to ensure that your specification will work for the data you are handling. A primary key of 'A0' through 'Z9' will only work for 26*10 = 260 values -- is this really what you want?
There are a few different approaches you can take in order to facilitate this behavior in SQL Server, so let's take a look.
Option 1: Determine the next value by querying a table
This first approach is usually the most common, and in my opinion also the worst. What people try to do here is to query the existing table to retrieve the last sequence value created, and then use that value to create the next one.
For example, you might create a User-Defined Function that you could use in a trigger like this:
This can cause some issues, however:
- What if two processes attempt to add a row to the table at the exact same time? Can you ensure that the same value is not generated for both processes?
- There can be overhead querying the existing data each time you'd like to insert new data
- Unless this is implemented as a trigger, this means that all inserts to your data must always go through the same stored procedure that calculates these sequences. This means that bulk imports, or moving data from production to testing and so on, might not be possible or might be very inefficient.
- If it is implemented as a trigger, will it work for a set-based multi-row INSERT statement? If so, how efficient will it be? This function wouldn't work if called for each row in a single set-based INSERT -- each NextCustomerNumber() returned would be the same value.
Overall, if this approach is absolutely required, then it's what you've got to do, but be sure that you consider the next two options first, which are much easier to implement and will generally work in most cases.
Option 2: Make it a presentation issue
The most common rules seem to be the simple ones, such as previous example ('C0000' to 'C9999'), or something similar. Looking at this closely, we see that it is really just simply a number from 1-x, formatted with leading zeroes to be 4 digits, and then prefixed with a 'C'. Which means that all the database needs to do is generate a number from 1-x, which means .. why not just use an identity and let your front-end format the sequence value? Do you really need to store it in the database as a VARCHAR? What does this gain? If you simply use an identity and return an integer to the front-end, it is trivial to format it with a 'C' in the front and with the necessary leading zeroes. By doing this, you have all of the advantages of a built-in SQL Server generated identity value with none of the headaches -- no worries about concurrency, performance, set-based triggers, and so on.
So, really carefully think to yourself: 'Do I really need to format a simple integer in T-SQL and store that formatted value in my tables? Or can I simply use that integer internally throughout the database and format it any way I want at my presentation layer?'
The advantage of this approach is simplicity, but the disadvantage is that you must rely on your front-end applications and reports to understand how to format your codes.
Option 3: Let an Identity be your guide
If you really need to store the actual, auto-generated sequence in your tables, or if a simple incrementing integer formatted a certain way isn't enough, there is another simple option: Use a regular identity column internally as your table's primary key, but then use some math to calculate your external 'auto-generated sequence' in another column using the identity value generated. This column can be stored in your table via a trigger, added as a computed column, or calculated using a View. You can implement it any way you wish.
The advantage of this approach is that we are using the database's built-in feature that guarantees that no two identities in a table will be alike, and that every row will get one; therefore, if we map each integer to a unique value in our sequence, we are guaranteed that all of our sequence values will also be unique. And this will work for set-based operations as well.
Let's start with the simple 'C0000' - 'C9999' example. First, let's create our Customers table like this:
Note that the dbID column is standard, database-generated identity which will be our physical primary key of the table. However, we will add a CustomerNumber column which will be what we expose to the outside world in the 'C0000' format, as described.
Let's create a function accepts an integer, and uses that integer to return our CustomerNumber:
Using that function, we can simply add a computed column to our table like this:
Return Auto Generated Key In Sql Server 2016
Or, we could also create a column in our table to store the Customer Number, and use a trigger to populate it:
Using either method, once they are in place, we can simply insert into our table, and for each Row added a unique 'Customer Number' is assigned:
The key to making this work is the formula that maps a 1:1 relation between integers and your sequence values.
That example was very trivial to implement; let's try some more complicated ones.
For example, suppose that the CustomerNumber will be in this format:
How can we take an integer and map it to this? In this case, it is the same way you convert digits from decimal to hexadecimal or any other 'base' -- we are converting from a base 10 (decimal) to base 26 (A-Z). Since we are working with a 4 'digit' value in base 26, this gives us 26 to the power of 4 different possibilities -- 456,976 different Customer Numbers can generated. (Remember the most important step before writing any code: is this acceptable?)
A simple algorithm to convert our integers to this base 26 number could be like this:
Starting with an integer identity value x:
- x mod 26 corresponds to the RIGHTMOST letter (0=A, 25=Z)
- x divided by 26 (26 to the power of 1) mod 26 corresponds to the NEXT letter from right to left
- x divided by 26*26 (26 to the power of 2) mod 26 corresponds to the NEXT letter, from right to left.
- x divided by 26*26*26 (26 to the power of 3) mod 26 corresponds to the LEFTMOST (first) letter.
To convert a number from 0-25 to a letter from A-Z, we add 65 to it and use the CHAR() function, since the ASCII value of 'A' is 65 and the rest of the letters all follow in sequence (i.e., 'B' is 66, 'C' is 67, etc).
Thus, to implement this method, our CustomerNumber function becomes:
Equally as important as writing the algorithm out on paper is then testing your implementation. We can do some simple testing like this to help us ensure that our function is working:
Return Auto Generated Key In Sql Server Download
And that appears to do what we need. You should of course test the higher values as well.
The key is that we have mapped our integer values using our function to Customer Numbers from AAAA-ZZZZ, all guaranteed to be unique, and we don't need to worry about set-based inserts or lookups on our existing table.
Let's try one more. How about
In this one, the left 2 digits are base 26; the right 3 are base 10. This gives us 26*26*10*10*10 = 676,000 possible values.
We use the same basic algorithm, starting from an integer x and working right to left:
- x mod 10 equals that is the rightmost digit
- x / 10 mod 10 equals the next digit
- x / 10*10 mod 10 equals the next digit
- x / 10*10*10 mod 26 equals the next letter
- x / 26*10*10*10 mod 26 equals the first letter.
Let's put this logic into a User Defined Function, which makes testing easier:
And let's test this function to ensure that it works:
And, again, that is just a guideline, but you should do as much testing as you can before implementing any of these features to ensure that they accurately do what you need. The key is to identify and test the 'boundary' numbers where the values need to reset or change in a more complicated manner than simply incrementing a single digit.
If you need to add dashes, or a constant prefix or suffix or anything else, you can easily do it as well, all in your UDF. The key is to make your logic entirely dependant on an integer value, and to map each integer value to a unique value in your designated sequence. By doing this, you are letting SQL Server do the hard part -- ensure that your keys are consistent and unique -- but now you have the flexibility of creating your 'CustomerNumbers' or other values in the exact format that you choose.
Summary
So, if you do find that you need to custom sequences of some sort at the database layer, here's my recommendation:
- Be sure that your code generation algorithm is well defined and handles your needs
- Be sure that it isn't just a presentation issue
- Write a UDF to map integers to your sequence values and let SQL Server generate those integers via an Identity column
- Test your UDF on its own thoroughly to ensure that it produces unique values in the format that you want
- Decide if a computed column, trigger, or View is the best way to incorporate these codes into your database layer
- Use identities internally as physical primary keys to your tables and for relations. (Note that this is optional; you may wish to use your sequence column, but be sure that it is indexed and constrained properly in your database.)
It can sometimes be tricky to come up with an algorithm and/or write the code to convert integers into your format, but if you can do it, I have found that in general it is the best approach to take.
Return Auto Generated Key In Sql Server Windows 7
Related ArticlesEfficiently Reuse Gaps in an Identity Column (9 February 2010) Implementing Table Interfaces (19 May 2008) Implementing Table Inheritance in SQL Server (20 February 2008) How to Insert Values into an Identity Column in SQL Server (6 August 2007) Using the OUTPUT Clause to Capture Identity Values on Multi-Row Inserts (14 August 2006) Windows 8 serial key generator online. The Case for the Surrogate Key (9 August 2002) Using TABLE Variables (7 June 2002) More Trees & Hierarchies in SQL (1 May 2002) | Other Recent Forum PostsError encountered while Creating a Publications (2h) Oracle developer Excel export daily (4h) Want to split the string after comma (5h) Making a simple webshop with SQL and C+ (11h) Job Truncates Data (14h) Convert Text to Date and Order By Date (1d) Migrating to a new server WEDNESDAY morning, April 15 (2d) Procedure edit for accumulated points (2d) |