Click here to Skip to main content
15,895,827 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
create sql str with special condition
hellow
I have 2 table
Table a(code, price, check)
Table b(code, percent)
I want to create a sql string such below:
SQL
Select a.code, a.price, (price * percent) as new_field
From a,b 
Where a.code = b.code

And this condition must be consider in sql str:
none
If (check = 1)
{
 New_field = price * percent
}
Else
{
 New_field = price * percent * 8
}

Now how can put above condition in sql str?
Thanks very much

[Edit]Code block added[/Edit]
Posted
Updated 22-Mar-13 7:18am
v2

1 solution

You should search for CASE statement on MSDN. This is basically what you need to handle conditions in your requests.

But there is something wrong in your query : you make a join between tables a and b, but you don't use table b in your SELECT part. Moreover, if you are using MS SQL Server, the syntax is incorrect. It should be:

SQL
SELECT
   a.code
  ,a.price
  ,CASE
     WHEN (a.check = 1) THEN (a.price * b.percent)
     ELSE (a.price * b.percent * 8)
   END
   AS new_field
FROM a INNER JOIN b ON a.code = b.code


[Edit] Included change with CASE statement
[Edit2] Replaced MSDN link with an english one
 
Share this answer
 
v6

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900