20 Mart 2014 Perşembe

Oracle/PLSQL: Sequences (Autonumber)

Learn how to create and drop sequences in Oracle with syntax and examples.

Description

In Oracle, you can create an autonumber field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key.

Create Sequence

You may wish to create a sequence in Oracle to handle an autonumber field.

Syntax

The syntax to create a sequence in Oracle is:
CREATE SEQUENCE sequence_name
  MINVALUE value
  MAXVALUE value
  START WITH value
  INCREMENT BY value
  CACHE value;

Example

Let's look at an example of how to create a sequence in Oracle. For example:
CREATE SEQUENCE supplier_seq
  MINVALUE 1
  MAXVALUE 999999999999999999999999999
  START WITH 1
  INCREMENT BY 1
  CACHE 20;
This would create a sequence object called supplier_seq. The first sequence number that it would use is 1 and each subsequent number would increment by 1 (ie: 2,3,4,...}. It will cache up to 20 values for performance. If you omit the MAXVALUE option, your sequence will automatically default to:
MAXVALUE 999999999999999999999999999
So you can simplify your CREATE SEQUENCE command as follows:
CREATE SEQUENCE supplier_seq
  MINVALUE 1
  START WITH 1
  INCREMENT BY 1
  CACHE 20;
Now that you've created a sequence object to simulate an autonumber field, we'll cover how to retrieve a value from this sequence object. To retrieve the next value in the sequence order, you need to use nextval. For example:
supplier_seq.NEXTVAL;
This would retrieve the next value from supplier_seq. The nextval statement needs to be used in a SQL statement. For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
VALUES
(supplier_seq.NEXTVAL, 'Kraft Foods');
This insert statement would insert a new record into the suppliers table. The supplier_id field would be assigned the next number from the supplier_seq sequence. The supplier_name field would be set to Kraft Foods.

Drop Sequence

Once you have created your sequence in Oracle, you might find that you need to remove it from the database.

Syntax

The syntax to a drop a sequence in Oracle is:
DROP SEQUENCE sequence_name;
sequence_name is the name of the sequence that you wish to drop.

Example

Let's look at an example of how to drop a sequence in Oracle. For example:
DROP SEQUENCE supplier_seq;
This example would drop the sequence called supplier_seq.

Frequently Asked Questions

One common question about sequences is: Question: While creating a sequence, what does cache and nocache options mean? For example, you could create a sequence with a cache of 20 as follows:
CREATE SEQUENCE supplier_seq
  MINVALUE 1
  START WITH 1
  INCREMENT BY 1
  CACHE 20;
Or you could create the same sequence with the nocache option:
CREATE SEQUENCE supplier_seq
  MINVALUE 1
  START WITH 1
  INCREMENT BY 1
  NOCACHE;
Answer: With respect to a sequence, the cache option specifies how many sequence values will be stored in memory for faster access. The downside of creating a sequence with a cache is that if a system failure occurs, all cached sequence values that have not be used, will be "lost". This results in a "gap" in the assigned sequence values. When the system comes back up, Oracle will cache new numbers from where it left off in the sequence, ignoring the so called "lost" sequence values. Note: To recover the lost sequence values, you can always execute an ALTER SEQUENCE command to reset the counter to the correct value. Nocache means that none of the sequence values are stored in memory. This option may sacrifice some performance, however, you should not encounter a gap in the assigned sequence values.
Question: How do we set the LASTVALUE value in an Oracle Sequence? Answer: You can change the LASTVALUE for an Oracle sequence, by executing an ALTER SEQUENCE command. For example, if the last value used by the Oracle sequence was 100 and you would like to reset the sequence to serve 225 as the next value. You would execute the following commands.
ALTER SEQUENCE seq_name
INCREMENT BY 124;

SELECT seq_name.nextval FROM dual;

ALTER SEQUENCE seq_name
INCREMENT BY 1;
Now, the next value to be served by the sequence will be 225.

12 Mart 2014 Çarşamba

Sqlite için MVC 5 Identity DB Scripti

Merhabalar, Microsoft harici teknolojilere ve projelere ilgimi herkes bilir. Özelliklede birçok projede bazen başlangıç aşamasında bazende projenin tamamında sql server harici veri tabanları kullanırım. En sık kullandığım ise Sqlite'dır. Stabil, küçük ve dll'ini sisteme eklemekten başka bir şeye ihtiyaç duymayan herhangi bir kurulum yapmanız gerekmeyen süper bir db motoru bu arkadaş. Özellikle nhibernate ile create table script'leri dahi yazmadan code first mimarisi ile çok rahat çalışabiliyor. Ancak problem microsoft'un gelişmesi için 10 yıl gereken entity framework aracında başlıyor. Sadece microsoft teknolojilerini doğal olarak destekleyen bu araç diğer yapılara "İsterseniz bana provider yazıp kendinizi ekleyebilirsiniz" mantığında. böylede olunca gözümdeki beş para etmez bir hale geliyor. ancak kendim kullanmayacak olsamda bazı yerlerde microsoft bir işe yarayacakmış gibi bu arkadaşın kullanımını zorunlu kılıyor. uzun lafın kısası 1. Entity Framework'ten hoşlanmadığımı anlamışsınızdır. Kullanmamanızı tavsiye ederim. NHibernate bu konuda bence en iyi araç. 2. Gelelim asıl konumuza eğerki mvc 5 ile yeni gelen Asp.Net Identity altyapısını kullanmak istiyorsanız ve bu konudaki http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity adresi ve benzeri adreslerdeki yazıları okuduysanız, hemen klavye başına geçip sqlite ile bu arkadaşı test etmeye kalkabilirsiniz. Ama maalesef bu konuda başarılı olamayabilirsiniz. Çünkü code first ile database'i generate ettiğini söyleyen entity framework provider yok gibi abuk bir hata vermekte. O zaman elinize baltayı alma zamanı gelmiştir. Bende tam öyle yaptım ve aşağıdaki script'i hazırladım. Bu script ile veri tabanınızı hazırlayıp sonrada bunun üzerinden Asp.Net Identity altyapısını kullanabilirsiniz.


CREATE TABLE [AspNetRoles] (
    [Id]   NVARCHAR (128) NOT NULL,
    [Name] NTEXT NOT NULL,
    CONSTRAINT [PK_AspNetRoles] PRIMARY KEY ([Id] ASC)
);


CREATE TABLE [AspNetUserClaims] (
    [Id]         INT            IDENTITY (1, 1) NOT NULL,
    [ClaimType]  NText NULL,
    [ClaimValue] NTEXT NULL,
    [User_Id]    NVARCHAR (128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY  ([Id] ASC),
    CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_User_Id] FOREIGN KEY ([User_Id]) REFERENCES [AspNetUsers] ([Id]) ON DELETE CASCADE
);

CREATE INDEX [IX_AspNetUserClaims_User_Id]
    ON [AspNetUserClaims]([User_Id] ASC);


CREATE TABLE [AspNetUserLogins] (
    [UserId]        NVARCHAR (128) NOT NULL,
    [LoginProvider] NVARCHAR (128) NOT NULL,
    [ProviderKey]   NVARCHAR (128) NOT NULL,
    CONSTRAINT [PK_AspNetUserLogins] PRIMARY KEY ([UserId] ASC, [LoginProvider] ASC, [ProviderKey] ASC),
    CONSTRAINT [FK_AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [AspNetUsers] ([Id]) ON DELETE CASCADE
);

CREATE INDEX [IX_UserId]
    ON [AspNetUserLogins]([UserId] ASC);


CREATE TABLE [AspNetUserRoles] (
    [UserId] NVARCHAR (128) NOT NULL,
    [RoleId] NVARCHAR (128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY  ([UserId] ASC, [RoleId] ASC),
    CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [AspNetRoles] ([Id]) ON DELETE CASCADE,
    CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [AspNetUsers] ([Id]) ON DELETE CASCADE
);

CREATE INDEX [IX_RoleId]
    ON [AspNetUserRoles]([RoleId] ASC);

CREATE INDEX [IX_AspNetUserRoles_UserId]
    ON [AspNetUserRoles]([UserId] ASC);


CREATE TABLE [AspNetUsers] (
    [Id]            NVARCHAR (128) NOT NULL,
    [UserName]      NTEXT NULL,
    [PasswordHash]  NTEXT NULL,
    [SecurityStamp] NTEXT NULL,
    [Discriminator] NVARCHAR (128) NOT NULL,
    CONSTRAINT [PK_AspNetUsers] PRIMARY KEY ([Id] ASC)
);


CREATE TABLE [__MigrationHistory] (
  [MigrationId] NVARCHAR(150) NOT NULL, 
  [ContextKey] nvARCHAR(300) NOT NULL, 
  [Model] NTEXT NOT NULL, 
  [ProductVersion] nvARCHAR(32) NOT NULL, 
  CONSTRAINT [] PRIMARY KEY ([MigrationId] ASC, [ContextKey] ASC)
);


örnek projeyi şu adresten inceleyebilirsiniz: https://github.com/alperkonuralp/AspNetMvc5WithSqlite