Auto increment a field without sequence in ORACLE - sql

I am trying to increment a field without sequence . Is there any possiblities??
can i do something like this
INSERT INTO Test
VALUES ((
SELECT COUNT(ID)
FROM Test)+1)
Please suggest me a way to do this

If your sequence field is called seq_fld for example you could use
insert into Test values ( (select max(seq_fld) from Test) + 1)
It is advisable to have unique constraint on seq_fld

you can take the current maximum value in a variable with #var_name = SELECT MAX(column_name) FROM TABLE
then you can make use of ROW_NUMBER() OVER (ORDER BY column_name)+#var_name

Related

Select last value in a specific column? (PostgreSQL)

Running into some issues when trying to retrieve the last value in a specific column, from a table and assign it into a variable.
Looking for the last int in a column "id" that is a primary key basically.
So I have a variable like "lastValue" in a select statement like :
select last(id) into lastValue from test_table
Not sure on an exact, or best way to accomplish this.
(on mobile, please forgive formatting)
A typical way to solve this is with order by and limit:
select id
from test_table
order by id desc
limit 1;
Of course, in this case, you could simply use:
select max(id)
from test_table;
But the first method allows you to choose whichever variables you want from the row with the maximum value.

SQL Server - how to update the ID column after inserting new records

I need to update a SQL Server table periodically by inserting new records into it.
The table has an ID column in the form of Company0001 through Company0020 right now.
Let's say I added one record of a new company into the table. I want to fill the ID column with Company0021 for this new record. Can anyone suggest a way to do this?
Thank you so much!
I would strongly suggest to use an identity column. Identity is a mechanism designed and used for this actual purpose and therefore it would be much better in terms of performance.
Nevertheless, if you insist on IDs on the format 'CompanyXXX' I would suggest to use a varchar column. Then you would add a trigger on the insert and update operations. When the trigger runs, it would find out the last 'CompanyXXX' and form the new one. If you need help regarding triggers, you could check this tutorial.
Hope I helped!
My suggestion would be to have an autoincrement field, and then concatenate the company name with the ID.
If you don't want to do it with an ID field, do you want it to happen automatically, or are you going to manage it manually? If automatically, you'll need to write a trigger to intercept the INSERT and change the value there. Shouldn't be too hard to do.
I'd seriously recommend NOT doing this and going down the autoincrement field path. It's better.
Add another column to the table to hold an integer value (in this example SNo) and then write query as
declare #SNo int
select #SNo=max(SNo)+1 from Table_Name
insert into Table_Namevalues (#SNo,'company'+right('0000'+cast(#SNo as varchar(10)),4))
And then see the result
Hope this helps
In case a solution is required as, having only one column with values in desired format you can create a function as:
create table table1(id varchar(100));
Go
create function dbo.fn_GetCompanyIdentity ()
returns varchar(100)
as
begin
declare #CompanyIdentify varchar(100);
select #CompanyIdentify =
(select 'Company' +
right ('00000' + cast (
(
(
case when Not exists (select ROW_NUMBER() over( order by (select 1)) from Table1 ) then 1
else (select top 1 ROW_NUMBER() over( order by (select 1)) as currentRownumber from Table1 order by currentRownumber desc) + 1
end
)
)
as varchar(4))
,4));
return #CompanyIdentify;
end;
go
and then use the function in insert statement as :
insert into Table1 (id)
select dbo.fn_GetCompanyIdentity();
Go
Hope this helps!!
Why dont you just create an auto-increment column and then concatenate "Company" to this column in another column. And for presentation just select "Company+autoincrement" column.

SQL -How to add an auto incremental id in a auto generated temporary table

I have a query like below and it generate a temporary table automatically based on parameter. So, the number of column of this table can be vary. Now , i need to add an auto incremental id column into this table.How i do it?
SELECT #SourceFields INTO ##StoreSourceInfo FROM testdb.dbo.#SourceTable
Note: 1) Number of source field & name of table pass using the parameter #SourceFields & #SourceTable.
2) So, the number of column can be vary on ##StoreSourceInfo table.
Current Result:
select * from ##StoreSourceInfo shows only the available column.
Expected Result:
select * from ##StoreSourceInfo query will show an additional auto incremental id column & all rest of the column available in the temp table.
Hope you get me. Thanks in advance.
SELECT
IDENTITY(INT, 1, 1) AS id
INTO #Temptable
FROM User
You can use row_number function
Select ROW_NUMBER() over (order by T.field1) rownum
, T.field1, T.field2 into #temp1
from #Table T
Use the identity function. See the link for an example. http://msdn.microsoft.com/en-us/library/ms189838.aspx
You have to try with following query to get your excepted result to add a extra auto increment column :
SELECT
IDENTITY(INT, 1,1) AS Rank,
#SourceFields
INTO
##StoreSourceInfo
FROM
testdb.dbo.#SourceTable
Means apply IDENTITY function...

Is there any editable Auto-Increment besdies IDENTITY?

The reason I need this for is that I made a column on my table called display_order, for now it's smallint and the numbers were pre-determined.
However, when I insert a new record with my software I don't know how to get the highest number in that column and add 1, so I thought about the possibility of an auto-incremented column where if I change 8 to 9 it will change everything else accordingly.
Is this possible?
The answer to your question is "No" IDENTITY is the only auto incrementing capability (and these columns are not updatable)
But if this is a display_order field can't you just make it float to allow you to insert items between other items rather than having to shift all other items down to create a gap?
However, when I insert a new record with my software I don't know how to get the highest number in that column and add 1,
Insert MyTable( display_order, .... )
Select (
Select Max(display_order) + 1
From MyTable As T1
), ...
From MyTable
However, I wouldn't recommend this. If display_order is user settable, then I would simply assume relative values. Thus, it wouldn't matter if a user added two values with a display_order = 0. If you really want to go the extra mile and provide the ability to resequence the display_order, you could do it like so:
Update MyTable
Set display_order = Z.NewSeq
From (
Select PKCol
, Row_Number() Over ( Order By display_order ) As NewSeq
From MyTable
) As Z
Join MyTable As T
On T.PKCol = Z.PKCol
Because you only get one IDENTITY column per table, I would probably use a trigger or other mechanism (if there's a centralized insertion stored proc) to default it to one more than the highest number in the table if not provided. This avoids having to SET IDENTITY_INSERT or anything like that.

select max value of a column in table with no rows

I am using oracle database
While inserting a row in a table, i need to find the max value of a column and increment it by 1, and use that value in row i am inserting.
INSERT INTO dts_route
(ROUTE_ID, ROUTE_UID, ROUTE_FOLDER)
VALUES (
(SELECT MAX(ROUTE_ID) + 1 FROM route) ,
ROUTE_UID,
ROUTE_FOLDER)
This works fine if their is at least one entry in table.
But returns null when their are no entries in table.
How can i get default value of 1 when their are no entries in table.
SELECT COALESCE(MAX(ROUTE_ID),0) ...
This is not a safe way of creating an auto-increment field. You can use an Oracle sequence to achieve this goal.
As for the null, you can use NVL to give a default value (say, 0) in case the function returns null.
Use sequence for the ID. You need to create sequence. See below link
http://www.basis.com/onlinedocs/documentation/b3odbc/sql_sequences.htm
Use:
INSERT INTO dts_route
(ROUTE_ID)
SELECT COALESCE(MAX(r.route_id), 0) +1
FROM ROUTE r
...but you really should be using a sequence to populate the value with a sequential numeric value:
CREATE SEQUENCE dts_route_seq;
...
INSERT INTO dts_route
(ROUTE_ID)
SELECT dts_route_seq.NEXTVAL
FROM DUAL;
Set a default for NULL
SELECT NVL(MAX(ROUTE_ID),0)
though using a sequence might be easier if you don't mind the odd gaps in your route ids
select 0 when null, then it will be 0+1 which is a correct number compared to null+1
SELECT isnull(MAX(ROUTE_ID),0) + 1 FROM route
If you are concerned about there being gaps in your route ids then create the sequence with the NOCACHE clause:
CREATE SEQUENCE dts_route_seq NOCACHE;
Note that there is a performance hit because Oracle now has to "commit" each time you increment the sequence.