views:

122

answers:

5

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?

+1  A: 

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.

Andrew from NZSG
I do not want it to be auto populated ,I want verification to be done.
vas
+1  A: 

You probably need to use a trigger rather than a constraint. An AFTER INSERT trigger should do the trick.

Vincent Ramdhanie
Since it appears a constraint can be written, it is better to put it in a constraint. Books Online even states that if you can use a trigger or a constraint it is better to use the constraint. Search for this in BOL to see what I meanconstraints [SQL Server], vs. DML triggers
HLGEM
+1  A: 

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.

Chris J
+1  A: 

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.

Mayo
Without knowing what country he's in, I'd avoid using purely numeric dates -- is this the 6 January or 1 June? It'd be safer to name the months instead.
Chris J
I am in US so mm/dd/yy
vas
@rangerchris - I agree with you completely, just throwing out pseudo code to illustrate the constraint concept. If it were actual code I would have used datediff... :)
Mayo
A: 

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
JuniorFlip