Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server add computed column in VIEW with conditions

Here is my situation:

In my table i two fields:

- Price (decimal (15,4)
- TaxId (int)

TaxId value is not stored anywhere but there are only two values (actualy 3).

- 1 (8.5%)
- 2 (20%)
- NULL (no tax)

Now i need calculated column in my view that would calculate new price with tax included.

Any idea?

I went with something like:

SELECT...
CASE TaxId
   WHEN 1 THEN Price *1.085 AS test
   WHEN 2 THEN Price *1.2 AS test
   WHEN NULL THEN Price  AS test END
FROM...

UPDATE:

I have managed to execute the query with success.

CASE dbo.Table.TaxId WHEN 1 THEN dbo.Table.Price*1.085 WHEN 2 THEN dbo.Table.Price*1.2 ELSE dbo.Table.Price END AS CalcualtedPrice

Now I only need to make CalculatedPrice as decimal (15,4). How can i set that?

like image 466
no9 Avatar asked Jun 06 '12 10:06

no9


People also ask

How do I add a calculated column to a SQL view?

Use SQL Server Management Studio In Object Explorer, expand the table for which you want to add the new computed column. Right-click Columns and select New Column.

Can a view contain computed or derived columns?

View is basically a select which is evaluated at runtime (Not considering Indexed views). So Like select, you can do any calculation or call any ufd for column in view ... The short answer is "yes", though methodology depends on which version of SQL you have.

Can you index a computed column?

Create indexes on persisted computed columnsYou can do this when the column is marked PERSISTED in the CREATE TABLE or ALTER TABLE statement. This means that the Database Engine stores the computed values in the table, and updates them when any other columns on which the computed column depends are updated.

Can we update computed column in SQL Server?

If we update the records in the SQL table, and computed columns calculate updated value once we retrieve data again. However, we cannot update or insert values in the virtual computed columns in SQL Server.


1 Answers

Yes, google how to create a view in SQL Server and in the SELECT statement of your view multiply the Price column with the TaxId column. Since you have to consider the NULL value you should use COALESCE like this

SELECT
Price * (1 + COALESCE(TaxId/100), 0) AS newValue
...

assuming that you have just '8.5' in your column and not '8.5%'. Is it varchar or not?

P.S.: COALESCE() returns the first non-null value

UPDATE after question was edited:

You just have to slightly modify your syntax

SELECT 
CAST(
CASE 
   WHEN TaxId = 1 THEN Price *1.085
   WHEN TaxId = 2 THEN Price *1.2
   WHEN TaxId IS NULL THEN Price END AS decimal(15,4)
) AS CalculatedPrice
FROM...
like image 190
fancyPants Avatar answered Oct 11 '22 14:10

fancyPants