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

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!!!

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

Trigger sum of two columns into 3rd SQL

I am trying to set a trigger in Microsoft Server Manager where a 3rd gets populated by a trigger
Eg. I have a table that contains
Column 1: Amount
Column 2: AdminFee
Column 3: TotalAmount
I need each new row in column3 (total amount) to be populated by Amount + AdminFee
I have the following script but it is not updating Column 3
CREATE TRIGGER UpdateActualAmount
ON Event
AFTER INSERT
AS
BEGIN
UPDATE BankTransaction
SET ActualAmount = Amount + AdminFee
END
GO
Can anyone let me know Where I am going wrong?
Run this one time:
ALTER TABLE BankTransaction DROP COLUMN ActualAmount;
ALTER TABLE BankTransaction ADD ActualAmount as (Amount+AdminFee)
Though tbh I'd be doing this in the front end as I don't really feel this kind of calculation has any business case for being part of the table..
If you're desperate to store the result of this sim as a table column and you want to index/query it, then make it a PERSISTED column..

Copy column with mathematic SQL Server

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.

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.

" If condition" as one of the constraints to a Column Field?

I have a Sales tax column in one of my SQL Table where Data is stored.
I was wondering is it possible to place an constraint on the table itself for the Sales Tax
Column saying " if > June 2008 tax is 2 % " else "tax is 4 %"?
Should that come from stored procs related to that Table?
If you want to make sure that the column 'tax' is 2 or 4 depending on the month (e.g., month 9 = September), then you could do this:
ALTER TABLE SomeTable
ADD CONSTRAINT CK_SalesTax
CHECK ((MONTH(GETDATE()) = 9 AND SalesTax = 2) OR (MONTH(GETDATE()) != 9 AND SalesTax = 4))
Obviously, vary for your conditions. e.g., to test for dates after June 2008, it's a bit simpler.
(GETDATE() >= '1 June 2008' AND SalesTax = 2)
You should be able to build this into a CHECK constraint of using a similar mechanism as I've dropped in the first example.
Note this only checks the value that put in to the table. It won't auto-populate. As other people have noted, if you want auto-population, you need a trigger.
Do you want the tax to be auto-populated?
Constraints only perform verification, not population of data, which can be done by stored procs or triggers.
You probably need to use a trigger rather than a constraint. An AFTER INSERT trigger should do the trick.
You could use a constraint to achieve this effect...
pseudo-SQL...
(YourDate >= '6/1/08' and YourTaxData = 0.02) or (YourTaxData = 0.04)
You might consider instead using a table to host the tax values and using your queries to pull the appropriate tax value for a given date/location. That's more scalable than the constraint.
here is a simple way you can alter or create a new table
create table #test (
Date datetime,
amount money,
tax as case when date > '06/01/08' then convert(decimal(10,2),4.00) else convert(decimal(10,2),2.00) end,
)
insert into #test
select '05/01/08', 10.00
insert into #test
select '07/01/08', 10.00
select * from #test