Create a new column based on other columns - sql

I've managed to create the following column in a new table:
CREATE TABLE t_issue_dates as
SELECT issue_d,
cast(substr(issue_d,5,4) as numeric) as issue_year
FROM myDB
(The code recodes a year-month variable to a year-only variable)
However, i can't add this variable to my existing table "myDB". I've tried using the:
ALTER TABLE myDB ADD v_year - command, but i can't manage to get it right.
Does anyone have an idea how i add the above variable to the "original" table myDB?
Thank you!

First, many databases support computed or generated columns. That means that you can add a virtual column to the database by doing:
alter table t_issue_dates add issue_year as (cast(substr(issue_d, 5, 4) as numeric));
I recommend this approach because issue_year is always up-to-date.
Second, you can do this as an actual column, but the value can get out-of-date and needs to be re-calculated for each inserted/updated row:
alter table t_issue_dates add issue_year numeric;
update t_issue_dates
set issue_year = cast(substr(issue_d, 5, 4) as numeric);
For the record, I would use int rather than numeric.

Assuming you are using MSSQL. It would be worth of reading documentation or a simple google on how to insert
Adding column :
Alter table t_issue_dates
Add V_year Int
Next step: This will only insert data for this particular column.
Insert into t_issue_dates (v_year)
SELECT
cast(substr(issue_d,5,4) as numeric)
FROM myDB

Related

How to copy SQL column data to new column then drop the original column?

I am following the recommendation in this sql snowflake forum in order to transform an integer data column into a varchar by creating a new column. I want to drop the original integer column when I am done, but doing so always results in the new column no longer working and any future queries erroring out.
For instance, I have test_num is the integer and test_num_to_char is the varchar
alter table test_table
add test_num_to_char varchar as CAST(test_num as varchar)
then
alter table test_table
drop column test_num
select *
from test_table
results in an error message:
SQL execution internal error: Processing aborted due to error 300002:224117369
Is there a different transformation method that removes the dependency on the original integer column so I can drop it?
alter table test_table add test_num_to_char varchar(10);
go
update test_table set test_num_to_char = CAST(recno as varchar);
Try the TO_DECIMAL transformation method.
It's documentation is given here

SQL Trigger to add values of Two columns and store it in Third column

i have a table with three columns say pqty,prqty and balqty.
what i want to do is, have to add values of pqty and prqty. and then it should be stored in balqty. while inserting or updating this table, each row must be affect.
i used this trigger, and it worked sometimes and most of times it wont. i dont know why.
CREATE TRIGGER tsl on stockledger
FOR update
AS declare #pqty int, #prqty int;
select #pqty=i.pqty from inserted i;
select #prqty=i.prqty from inserted i;
update Stockledger set balqty = (#pqty - #prqty)
PRINT 'AFTER Update trigger fired.'
I don't think this is a good use of a trigger. Instead, if you have the capacity, consider using a computed column (with PERSISTED to enhance performance):
ALTER TABLE StockLedger DROP COLUMN balqty;
ALTER TABLE StockLedger ADD COLUMN balqty AS pqty - prqty PERSISTED;

Creating a sequence on an existing table

How can I create a sequence on a table so that it goes from 0 -> Max value?
I've tried using the following SQL code, but it does not insert any values into the table that I am using:
CREATE SEQUENCE rid_seq;
ALTER TABLE test ADD COLUMN rid INTEGER;
ALTER TABLE test ALTER COLUMN rid SET DEFAULT nextval('rid_seq');
The table I am trying to insert the sequence in is the output from another query. I can't figure out if it makes more sense to add the sequence during this initial query, or to add the sequence to the table after the query is performed.
Set the default value when you add the new column:
create sequence rid_seq;
alter table test add column rid integer default nextval('rid_seq');
Altering the default value for existing columns does not change existing data because the database has no way of knowing which values should be changed; there is no "this column has the default value" flag on column values, there's just the default value (originally NULL since you didn't specify anything else) and the current value (also NULL) but way to tell the difference between "NULL because it is the default" and "NULL because it was explicitly set to NULL". So, when you do it in two steps:
Add column.
Change default value.
PostgreSQL won't apply the default value to the column you just added. However, if you add the column and supply the default value at the same time then PostgreSQL does know which rows have the default value (all of them) so it can supply values as the column is added.
By the way, you probably want a NOT NULL on that column too:
create sequence rid_seq;
alter table test add column rid integer not null default nextval('rid_seq');
And, as a_horse_with_no_name notes, if you only intend to use rid_seq for your test.rid column then you might want to set its owner column to test.rid so that the sequence will be dropped if the column is removed:
alter sequence rid_seq owned by test.rid;
In PostgreSQL:
UPDATE your_table SET your_column = nextval('your_sequence')
WHERE your_column IS NULL;
I'm not fluent in postgresql so I'm not familiar with the "CREATE SEQUENCE" statement. I would think, though, that you're adding the column definition correctly. However, adding the column doesn't automatically insert data for existing rows. A DEFAULT constraint is for new rows. Try adding something like this afterwards to populate data on the existing rows.
DECLARE #i Int
SET #i = 0
SET ROWCOUNT 1
WHILE EXISTS (SELECT 1 FROM test WHERE rid IS NULL) BEGIN
UPDATE test SET rid = #i WHERE rid IS NULL
END
SET ROWCOUNT 0

How to change column varchar to clob in oracle

I have a column details designed as varchar in oracle DB, this DB is being used now for customers and some rows already have data stored.
Now I want to change the column details to a Clob column. What is a smart way to accomplish this?
(as the previous answer) and here's the code:
ALTER TABLE atable
ADD (tmpdetails CLOB);
UPDATE atable SET tmpdetails=details;
COMMIT;
ALTER TABLE atable DROP COLUMN details;
ALTER TABLE atable
RENAME COLUMN tmpdetails TO details;
Add a clob column to the table
update clob column with values from varchar column
drop varchar column
rename clob column to varchar columns name
But this will not maintain the position of your column. It will move your column to the end of table. So if you want to maintain the position of your column as well follow these steps.
alter table atable add (tempdetails varchar2(4000));
update atable set tempdetails = details;
update atable set details = null; -- this is necessary to change data type
alter table atable modify details long; -- this is required because you can not change directly to clob.
alter table atable modify details clob;
update atable set details=tempdetails;
alter table atable drop column tempdetails;
This is the way in which you will maintain the data and position of your column intact even after changing the datatype. For detail information with example see here : http://www.oraclebin.com/2012/12/how-to-change-varchar2-to-clob-datatype.html
if you need your table data to be accessible during the process.. look at
DBMS_REDEFINITION
see a similar question on asktom
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1770086700346491686

How to alter a column datatype for derby database?

I am trying to alter a datatype for a derby db column. The current price column is set as DECIMAL(5,0). I would like to alter it to DECIMAL(7,2). I did this :
alter table item alter column price set data type DECIMAL(7,2);
But it did not work, and showing the error:
Error: Only columns of type VARCHAR may have their length altered.
May I know how is it possible to alter it? Thank you.
Here is the Derby SQL script to change column MY_TABLE.MY_COLUMN from BLOB(255) to BLOB(2147483647):
ALTER TABLE MY_TABLE ADD COLUMN NEW_COLUMN BLOB(2147483647);
UPDATE MY_TABLE SET NEW_COLUMN=MY_COLUMN;
ALTER TABLE MY_TABLE DROP COLUMN MY_COLUMN;
RENAME COLUMN MY_TABLE.NEW_COLUMN TO MY_COLUMN;
I think you can do like this:
ALTER TABLE SCHEMA.TABLE ALTER "COLUMN-NAME" SET DATA TYPE VARCHAR(255);
(column-Name SET DATA TYPE VARCHAR(integer)) for Datatype String as an example...
Here's a slightly more complicated way to alter the column's data type in this fashion:
Add a new column, of the desired data type
Issue "update ... set new-column = old-column to copy the data from the old column to the new column
drop the old column
Rename the new column to have the name of the old column.
Slightly more steps, but in the end the effect will be the same.
If you have trouble working out the exact details of the SQL to do this, let us know and we'll help.
You can alter table like this:
ALTER TABLE [table] ALTER COLUMN [column] SET DATA TYPE [type];
Or in Rails, just use:
change_column :table_name, :column_name, :integer
Posgtes Solution :
ALTER TABLE prices_table ALTER price_column TYPE decimal (7,2 )