Click here to Skip to main content
15,916,941 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to implement two queries using store procedure


first i want to use count query to check wheather the product already exits or not. then if the product doesn't exit. then i want to insert a data. other wise throw an error that record already exits.

i want to implement such kind of thing in storeprocedure.. but don't know how to do..

C#
query= Select Count * from ShoppingCart where Productid='"+@productid+"'

int count= obj.ohh(query)
if(Count>)

{
Response.Redirect("Error Page.aspx")

}
else

INSERT INTO SHOPPINGCART
	(CUSTOMERID,PRODUCTID,QUANTITY) 
	VALUES(@CustomerID,@ProductID,@Quantity
)
Posted

CREATE PROCEDURE [PROCEDURENAME]
@PRODUCTID INT,
AS

DECLARE @COUNT INT,
SELECT @COUNT = SELECT * FROM SHOPPINGCART WHERE PRODUCTID=@PRODUCTID
IF(@COUNT>0)
RAISERROR('YOUR MSG', 16, 1)
ELSE
INSERT INTO SHOPPINGCART
(CUSTOMERID,PRODUCTID,QUANTITY)
VALUES(@CustomerID,@ProductID,@Quantity)
 
Share this answer
 
Comments
P.Salini 24-Sep-11 2:54am    
I think in 1st query you need to specify count(*) instead of *
Hi
You can simply do

SQL
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddToCart] 
	@CustomerID varchar(50),
	@ProductID int,
	@Quantity int
As
If Not Exists (Select 1 From table where ProductID = @ProductId)
 INSERT INTO ShoppingCart	(CustomerID,Quantity,ProductID) VALUES(@CustomerID,@Quantity,@ProductID)
 
Share this answer
 
Something like this (probably needs tweaking):

C#
query = "declare count int;set count = select count (*) from table where blah=blah; if (count = 0) insert into table blah blah;"
SqlCommand cmd = new SqlCommand(query, conn);
int recsAffected = sqlCommand.ExecuteNonQuery();
if (recsAffected == 0)
{
    Response.Redirect("Errorpage.aspx");
}
 
Share this answer
 
Comments
codegeekalpha 23-Sep-11 16:07pm    
i want to do it using store procedures..
codegeekalpha 23-Sep-11 16:14pm    
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddToCart]
@CustomerID varchar(50),
@ProductID int,
@Quantity int,
@Count int
@Count=select count (*) from table where ProductID=@ProductID;
If(@Count==0)
AS
BEGIN
INSERT INTO ShoppingCart
(CustomerID,Quantity,ProductID)
VALUES(@CustomerID,@Quantity,@ProductID)
END
codegeekalpha 23-Sep-11 16:14pm    
i wrote it like this but getting error
Rajesh Anuhya 23-Sep-11 23:23pm    
can you give me what error you are getting??

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