Copy column with mathematic SQL Server - sql

I'm new to SQL Server. I have column with value of product, now I want to add column value + tax (tax = 10% value) on the same table. Any suggestion how to do this the fastest way or should I insert 1 by 1? Can I just copy value column and add some mathematics ? If I can do that can someone show how it work? Thanks.

If the tax is always the same, you can use a computed column:
alter t add value_plus_tax as (value * 1.1);
This calculates the value whenever you need it. Otherwise, you should add the column explicitly and update it:
alter t add value_plus_tax decimal(10, 2); -- or whatever
update t
set value_plus_tax = value * 1.1;

If your tax rate can change, you can store the rate in a separate table and use a view that joins the two tables to retrieve the data...
CREATE TABLE TaxRate (
[Percent] TINYINT
)
GO
CREATE VIEW ValuesWithTax AS
SELECT *, [Value] * [Percent] / 100 ValueWithTax FROM [Values]
CROSS JOIN TaxRate

If tax rate is not a fix value, you can add a column to save tax rate and a computed column to save total value
ALTER TABLE table1 add tax_rate decimal(19,4) DEFAULT(0.1) WITH VALUES
ALTER TABLE table1 add toatal_value as ([value](1+tax_rate))

Add computed column like (having all calculation).
Ie : Below example i have considered sum of value and tax column you can do any calculation (Make sure the calculation should not throw exception consider boundary condition ) .
ALTER TABLE dbo.tableName ADD RetailValue AS (value+tax );
you can make it persisted computed column too.

Related

Store a calculated math equation in a Query?

I am working on this:
I would like to know how to create a new column that holds the amount equal to LocalCurrency multiplied by ExchangeRate for each rows of item.
Use a computed column:
alter table t add newcolumn as (localcurrency * exchangerate);
This adds the column to the table so it is calculated automatically when you retrieve it. The value is automatically set so no update is needed.
You can calculate when required in a query or can create a view to do so and use it wherever required.
CREATE VIEW Purchase_details AS
SELECT *, localcurrencyamount*exchangerate
FROM your_table_name
Select * from Purchase_details

change type of a computed column to uncomputed in sql

I have some computed columns in my DB with data. Is there anyway to change type of those columns to uncomputed without dropping and copying their data into new uncomputed columns?
For example I want to change
[Fee] AS CONVERT([decimal](19,4),(case when [Quantity]=(0) then (0) else [Price]/[Quantity] end)) PERSISTED,
to
[Fee] [decimal](26, 16) NOT NULL,
The exact answer is "it depends." MySQL doesn't even have computed columns. In SQL Server, I don't think it is possible. In Oracle it can be done with alter table t1 modify fee DECIMAL( m, n ).
However, even when allowed, the DBMS is probably behind the scenes creating a new column, moving the computed value to the new column, dropping the computed column and renaming new column to computed column name. So even if the conversion is not explicitly allowed, you can still get it done.
Computed Columns do not store data in themselves.
When you try to select the column in a query it computes the data and shows you. Also you can not modify computed columns to uncomputed columns.
But you can do this instead:
Create Table Temp (ID BigInt, value Computed_Column_DataType)
Go
Insert Temp(ID, Value)
Select ID, ComputedColumnName
From Your_Table
Go
Alter Table Your_Table Drop Column ComputedColumnName
Go
Alter Table Your_Table Add ComputedColumnName Computed_Column_DataType
Go
Update Your_Table Set ComputedColumnName = A.Value From Temp A Where A.ID = YourTable.ID

Adding a column which uses other column fields as operands for operation like addition and percentage calculation

ALTER PROCEDURE [dbo].[Sp_TotalMarks]
AS
BEGIN
SELECT Student_Id, Stu_Name, Maths, English, Hindi,
(Maths + English + Hindi) AS 'Total',
CAST(CAST((Maths + English + Hindi) AS NUMERIC(8,2)) / 300 * 100 AS NUMERIC(8,2)) AS 'Percentage'
FROM tbl_Marks
END
This is the procedure which I am using to display percentage.
If there are 100 students in a class and I want to display the percentage of each one of them then the SP which dynamically calculates the %age and returns the answer , will be time consuming. Earlier I was trying to add a column of percentage in tbl_Marks itself.Is it possible to implement trigger in the store procedure which is called on 'INSERT' or 'UPDATE' operation on the tbl_Marks. I have never used trigger actually. If you could explain me the solution of this problem with a query It would be great. Thanks in advance.
A computed column can use data from other columns of the table to calculate a value for the column to which it belongs.Also a computed column is a virtual column that is not physically stored in the table, unless the column is marked PERSISTED.
So alter your table definition as:
ALTER TABLE tbl_Marks ADD total AS (Maths + English + Hindi) PERSISTED;
ALTER TABLE tbl_Marks ADD Percentage AS CAST(CAST((Maths + English + Hindi) AS NUMERIC(8,2)) / 300 * 100 AS NUMERIC(8,2)) PERSISTED;
This will add two columns to the table which will reflect the computed values on each update or insert.
You can check the DEMO here. Hope this helps!!!

Multiplying two columns of same table and storing result to the third column of same table

I m having a table
SALES(sno,comp_name,quantity,costperunit,totalcost)
After supplying the costperunit values, totalcost need to be calculated as "totalcost=quantity*costperunit".
I want to multiply 'quantity' and 'costperunit' columns and store the result in 'totalcost' column of same table.
I have tried this:
insert into SALES(totalcost) select quantity*costperunit as res from SALES
But It failed!
Somebody please help me in achieving this..
Thanks in Advance
Try updating the table
UPDATE SALES SET totalcost=quantity*costperunit
You need to use update.
UPDATE SALES SET totalcost=quantity*costperunit
It would be better if you do not calculate this field manually but make it a computed column instead - so it calculates automatically for you.
You can change the column with following query:
ALTER TABLE Sales
DROP COLUMN totalcost
ALTER TABLE Sales
ADD totalcost AS quantity*costperunit
DEMO
try this while inserting new row
INSERT INTO test(sno,comp_name,quantity,costperunit,totalcost)
Values (1,#comp_name,#quantity,#costperunit,#quantity*#costperunit)
Best not to store fields that can be calculated, but if you want to, with SQL Server you can set a field to be calculated automatically when values are there.

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.