add not null column take values from other column - sql

I have an existing table say, Items with Id | CreateDate (as DateTime) columns; want to add Year int not null, take the default year from the CreateDate column.
The Year value will be futer updated to different value, but just set it as default value when the column Year is added, because want to add non-nullable column to Year.
Is that possible?

If you want to add a new column and initialize it with the values from the other one, you can do:
-- add the column (as nullable)
alter table mytable add created_year int;
-- update the values on existing rows
update items set created_year = year(created_date);
-- make the column not nullable
alter table mytable alter column created_year int not null;

Don't bother with another column -- unless you will feel the need to change the value of the column in the future. Instead, just use a computed column:
alter table t add created_year as (year(created_date));
This is automatically calculated when you query the table, so it is always accurate, both for new rows and old rows.
Presumably, created_date is never updated.

Related

Add a column with a value computed from other columns in SQL without using the default value

I can add a column this way:
ALTER TABLE MyTable
ADD MyColumn BIT NOT NULL
CONSTRAINT MyConstraint
DEFAULT 0
Now, instead of the constant 0 I want to put a different value depending on my other columns in the MyTable. I.e. it is a one time computation during the column addition. How could I do that?
Also, I do not want my column to have a default value.
E.g. I have another BIT column called MyOldColumn and I want to just copy its value into the MyColumn.
Looks like you just want to add the column, then run an update using some calculation.
ALTER TABLE MyTable ADD MyColumn BIT;
UPDATE MyTable
SET MyColumn = SomeCalculation;
ALTER TABLE MyTable ALTER COLUMN MyColumn BIT NOT NULL;
Why set the column to null first then not null? Because it will be more performant. Setting it to null first means it's a meta-data only operation, and will not change the data pages. The final ALTER will also not change any pages (although it will read them all), because none of them are null.
Whereas if you set it to not null first then all pages get changed, and then changed again.

Filling in a datetime field as empty

I need to add a new record to a database and one of the columns in my table is 'paymentDate', which is a "DateTime" field. Now the record I need to add is one in which the paymentDate is not known. I can't put in 'NULL' as SQL says 'Column 'paymentDate' cannot be null'. Also the '""' doesn't work in a datetime field.
If you have a paymentDate column and you don't know the date, then the column should allow NULL values. So, you should fix the data model:
alter table t alter column paymentDate datetime;
This will remove the not-NULL constraint, so you can add the data that you have.
I would be a little cautious, though. Why are you trying to add a row with an unknown payment date, if the designer of the table thought the value should never be NULL?

How best to sum 2 columns and update 3rd column with sum?

I am looking for the best way to add 2 or more columns in a SQL Server table and update another column with there sum.
Yes, I know this is a dumb thing to do and calculations should be done at time of transaction but I am modifying an existing table where the data in a column now needs to be more detailed but numerous processes will still use the column value.
For example, a column name is TotalDailyMiles and numerous processes access and use that field. Now more detail is needed. 2 columns need to be added to the table TotalAMMiles and TotalPMMiles. These 2 columns will sum to the existing column. Changing all the processes that access the TotalDailyMiles column to use the 2 new columns instead is not an option. The data for the new columns in old records does not exist so the value for columns holding the sum of the 2 new columns cannot be based on the 2 new columns in old records because in old records the new column values will be 0, or maybe null but I'm leaning toward 0 so I can set the new columns as Not Null.
I'm thinking of using a trigger to update the column holding the sum based on the new columns changing but I'm hoping one of you smart people have a better option.
How about treating the existing column as its own value (which will be 0 in future rows), adding the two new columns, and then creating a calculated column with the same name as the old Total? Something like this (I'm assuming a data type of decimal(7, 2) but of course use what you have, though I hope it's not float):
EXEC sp_rename 'dbo.Miles.TotalDailyMiles', 'DailyMiles';
ALTER TABLE dbo.Miles ADD COLUMN AMMiles decimal(7, 2) NOT NULL
CONSTRAINT DF_Miles_AMMiles DEFAULT (0);
ALTER TABLE dbo.Miles ADD COLUMN PMMiles decimal(7, 2) NOT NULL
CONSTRAINT DF_Miles_PMMiles DEFAULT (0);
ALTER TABLE dbo.Miles ADD COLUMN TotalDailyMiles
AS (DailyMiles + AMMiles + PMMiles) PERSISTED;
Some possible housekeeping that might be needed on the DailyMiles column, too:
-- if not already NOT NULL
ALTER TABLE dbo.Miles ALTER COLUMN AMMiles decimal(7, 2) NOT NULL;
-- if not already defaulting to 0
ALTER TABLE dbo.Miles ADD
CONSTRAINT DF_Miles_DailyMiles DEFAULT (0) FOR DailyMiles;
You could additionally add a constraint that either DailyMiles must be 0, or AMMiles and PMMiles must both be 0:
ALTER TABLE dbo.Miles ADD CONSTRAINT CK_Miles_DailyOrAMPM
CHECK (DailyMiles = 0 OR (AMMiles = 0 AND PMMiles = 0));
As long as consumers of the data don't try to update the TotalDailyMiles column, you've solved your problem handily.

Adding a new column in a temporary table

I have a temporary table in a PostgreSQL function and I want to insert a new VARCHAR column. It should have a value that depends on another column of the table, named "amount".
When the amount is positive I would like the value of the column row to be credit and when the value is negative the column should be debit.
I have one more request: I want to round the value of amount column in 2 decimal digits
You want ALTER TABLE ... ADD COLUMN followed by an UPDATE.
I initially said ALTER TABLE ... ADD COLUMN ... USING but that was wrong on two counts. ADD COLUMN takes a DEFAULT not USING - and You can't do it in one pass because neither a DEFAULT expression nor a USING expression may not refer to other columns.
So you must do:
ALTER TABLE tablename ADD COLUMN colname varchar;
UPDATE tablename SET colname = ( CASE WHEN othercol < 0 THEN 'Credit' ELSE 'Debit' END );
Think carefully about whether zero should be 'Debit' or 'Credit' and adjust the CASE accordingly.
For rounding, use round(amount,2). There isn't enough detail in your question for me to be sure how; probably by UPDATEing the temp table with UPDATE thetable SET amount = round(amount,2) but without the context it's hard to know if that's right. That statement irreversibly throws information away so it should only be used on a copy of the data.

How to insert columns in between in table in sql server 2008

I want to add or update columns using alter table if i am adding a new column i want show error. I am using the code below
alter table Personal_Details alter columns DOB datetime
if i uncheck the NULL to not NULL then it will shows column does not allow nulls; update fails;
i want to insert the fields in between columns not at end.
Plese fix my bug,
Thanks in advance.
The position of the column in the table declaration has nothing to do with its being NULL or NOT NULL.
If you are adding a column (of any type) which you want to be NOT NULL, i.e. you want to prohibit NULL values in that column, and the table already contains some rows, you must also provide some default value. For example:
ALTER TABLE Personal_Details
ADD COLUMN DOB datetime NOT NULL DEFAULT (GETDATE())
Otherwise the engine will attempt to add that column with NULLs as its values, which will violate the NOT NULL property, and the change, therefore, will be reverted.
Basically, the same applies when you want to set an existing column's NOT NULL property on while the column already contains NULLs. But in this case you must explicitly eliminate the NULLs before the change by either replacing them with values or removing the respective rows.
Source:
ALTER TABLE (Transact-SQL). (The particular section related to your problem is just above this code snippet.)
1)For ur adding column with not null problem
Use
ALTER TABLE Personal_Details ADD COLUMN DOB datetime NULL
Update the DOB column with the required dates and make sure there is no null in the column
then alter the column using
ALTER TABLE Personal_Details ALTER COLUMN DOB datetime not NULL
2)For your column going to the end problem...
you should not be worried...the order in which the columns are arranged doesnt matter...unless u are using a pathetic way of accessing data by column order..in which case again..u should stop accessing it by column order...
If the column order really matters you can change it using design option in the sql management table(rightclick on table >design and drag the column to its required place.)