How can I add an autoincrementing ID field to a table in SQL-SERVER starting from X - sql

I have a table in SQL server right now, and I want to add the column PART_NO to it. It needs to be auto incremented (1,2,3 etc) starting from the number 107.
How can I do something like this?

Using alter table add to add a column with the identity(autoincrementing) property using identity() you can set the seed value for the first row, and the increment number. identity(seed,increment).
alter table [tbl] add part_no int identity (107,1) not null;

Use the following command
Alter table tablename add columnname int identity <starting number,incremented by> not null;

Related

How to add new column using CAST and info from another table in SQL?

I'm trying to understand the relationship between two operations in SQL - ADD COLUMN and CAST().
I tried to create a new column containing the lengths of another column's values, while that other column is inconveniently of type INTEGER:
ALTER TABLE inventory
ADD inventory_id_len AS (CHAR_LENGTH(CAST(inventory_id AS VARCHAR)) FROM rental);
But it returns:
ERROR: syntax error at or near "AS"
LINE 4: ADD inventory_id_len AS (CHAR_LENGTH(CAST(inventory_id AS V...
Thanks.
In Postgres, you need to use the generated always ... stored syntax to add a computed column. For your use case, that would look like:
alter table inventory
add inventory_id_len int
generated always as (char_length(inventory_id::text)) stored
;
A subquery makes no sense in that context; the computed column takes the value of column inventory_id on the very same row.
If you want to add the length of the id as a generated column:
ALTER TABLE inventory
ADD inventory_id_len INT GENERATED ALWAYS AS (LEN(inventory_id::text) STORED;
Because Postgres does not (yet) support virtual generated columns, a view might be more in line with what you want:
create view v_inventory as
select i.*, len(inventory_id::text) as inventory_id_len
from inventory i;

Microsoft SQL Server - Copy column in table, modify value and type

I'm quite new to scripts and need some help on creating a script doing multiple actions in sequence.
Let's use this tentative (and bisarre) table to illustrate the solution. The table could potentially hold hundreds of entries:
I want to add a PhoneNumber column with varchar type and populate it from the existing PhoneNumber column.
For phone numbers consiting of 5 digits I want to add a leading zero (0) so all entries have the same length (6).
When this is done for all occurances of 5-digit phone numbers I want to delete the old PhoneNumber column
This is how the table should look after step 1:
And after step 2 it should look like this:
Finally, after the third step I want this outcome:
Can this be accomplished with a script? I don't really need the script to follow this exact sequence as long as it results in the desired outcome. This is just the sequence of actions I have thought could be an allright approach.
Here you go
Remember, you can't have 2 columns called the same
ALTER TABLE [TABLENAME] ADD PHONENUMBERCHAR char(6); --Adds a new column
GO;
UPDATE [TABLENAME] SET PHONENUMBERCHAR = RIGHT(CONCAT('000000', PHONENUMBER), 6); --Updates the value
GO;
ALTER TABLE [TABLENAME] DROP COLUMN PHONENUMBER --Deletes the old column
If the value is really an integer, you can use format():
select id, phonenumber, format(phonenumber, '000000')
from t;
You may want to add this as a computed column:
alter table t add phonenumber_6 as (format(phonenumber, '000000'));

How to auto_increment a value from a column when inserting a new row

I know that it seems similar to some questions, but I hope mine is different.
I work with an Oracle Database
I want to have an auto_increment on a column by using
COMPUTED column and LAST_VALUE(column) + 1
So I have the following request :
ALTER TABLE schema.table (
ADD SK NUMBER ALWAYS AS (LAST_VALUE(SK)+1)
);
Is it gonna do the trick with only that ?
Or do I need to add a FOR EACH ROW sentence so that fits with my need of auto_increment ?
EDIT According to G00dy's comment:
The sequence :
create sequence SK_SEQUENCES
increment by 1
start with 1
nomaxvalue
minvalue 1
nocycle
order
keep;
The table :
create table schema.test(
isCurrent CHAR(10),
SK NUMBER
);
If I understand the comment from #g00dy,
I need to add the Sequence as a value for my column SK,
so I have this :
insert into schema.test(SK)
values (SK_SEQUENCES.nextval)
Then ok, it works
But when I'm adding value to the isCurrent column,
there's no auto_increment on the SK column
I guess, to have the auto_increment I need to create a trigger.
Maybe I'll have to use trigger/sequence in order to fix my issue but I don't want to..
No, it won't work.
Firstly, the syntax is generated always, not just always, and there are no brackets around the add clause. However, this still won't work:
alter table demo
add sk integer generated always as (last_value(sk)+1);
fails with:
ORA-30484: missing window specification for this function
because last_value is an analytic function that needs to be part of a query and have a window specification like over (partition by xxx order by yyy). You can't use an analytic function as a column default.
From Oracle 12.1 you can define an identity column as:
alter table demo
add sk integer generated always as identity;
In earlier Oracle versions you would need to either specify the sequence.nextval when inserting, or else create a trigger as
create sequence sk_seq;
create or replace trigger demo_generate_sk_trg
before insert on demo for each row
begin
:new.dummy := sk_seq.nextval;
end;
/

SQL simplist way to update an INT identity column

I have a column called fixedID, and it's current Value = 2, I want to update this value to be 42. What is the best way to do this. I would like to do this modification as simply as possible. However, if I could do this while doing an select insert that would be fantastic also.
update tblFixedId
set FixedId = (FixedId + 400)
possible to change the value here?
Select * INTO mynewTable from myOldertable
Identity columns are not updatable in SQL Server.
The only way of doing this as an actual UPDATE rather than a DELETE ... INSERT would be to use ALTER TABLE ... SWITCH to mark the column as no longer an IDENTITY column, do the UPDATE then ALTER TABLE ... SWITCH again to re-mark the column as IDENTITY (For example code the first way round see the workarounds on this Connect Item and for the second way here).
Note that in the common scenario that the identity column is the clustered index key the Update will likely be implemented as an INSERT ... DELETE anyway.

Adding a column after another column within SQL

How do I add a column after another column within MS SQL by using SQL query?
TempTable
ID int,
Type nvarchar(20),
Active bit
NewTable
ID int,
Type nvarchar(20),
Description text,
Active bit
That is what I want, how do I do that
Assuming MySQL (EDIT: posted before the SQL variant was supplied):
ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn
The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.
It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:
ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;
In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:
ALTER TABLE name ALTER column POSITION new_position
I guess it may work in other cases as well.