Friday, March 23, 2012

How to test if record is found or not and do different things accordingly in a query

I want to do something like

if "Product_code" is Null

insert dbo.t_Shopping_cart (Product_code,Name,Price,Product_group,Quantity,Total)
select Product_code,Name,Price,Product_group,Quantity=1,Yhteensa=1
FROM dbo.t_Shopping_cart
WHERE Product_code='AHTU140213'

else

update dbo.t_Shopping_cart
set Quantity=Quantity+1
where Product_code='AHTU140213'

In short: I cant test existence of a record.

Regards

Leif

IF @.Product_codeISNULLBEGININSERT dbo.t_Shopping_cart (Product_code,Name,Price,Product_group,Quantity,Total)SELECT Product_code,Name,Price,Product_group,Quantity=1,Yhteensa=1FROM dbo.t_Shopping_cartWHERE Product_code= @.Product_CodeENDELSEBEGINUPDATE dbo.t_Shopping_cartSET Quantity=Quantity+1WHERE Product_code=@.Product_CodeEND

|||

IFNOT EXISTS(SELECT *FROM dbo.t_Shopping_cartWHERE Product_code=@.Product_code)BEGININSERT dbo.t_Shopping_cart (Product_code,Name,Price,Product_group,Quantity,Total)SELECT Product_code,Name,Price,Product_group,Quantity=1,Yhteensa=1FROM dbo.t_Shopping_cartWHERE Product_code= @.Product_CodeENDELSEBEGINUPDATE dbo.t_Shopping_cartSET Quantity=Quantity+1WHERE Product_code=@.Product_CodeEND
|||

This looks interesting. I will certainly try it later tonight.

A couple of short questions.

By the way, is it @.Product_code and not Product_code in "IF @.Product_codeISNULL"line.


If it is possible to write Yhteensa=1, which means total=1 by the way, why isn't this possible "Yhteensa=Price*Quantity". I tried it in Management Studio.

Many thanks

Leif

No comments:

Post a Comment