Click here to Skip to main content
15,894,460 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I want to UPdate my table if some condition Takes place

if not i want to insert to my table

but i have errore in my code for some reason can anybody tell me what is my errore

SQL
ALTER PROC [dbo].[SqldataTable]
@id real,
@prod nvarchar(50),
@category varchar(50),
@price real,
@instock bit,
@count real,
@DateUpdate datetime,
@description nvarchar(max)
 

as
--somthing wrong here!
if  (ID like @id)

begin


UPDATE  [DBT] 
set

ID=@id,
ProductName=@prod,  
Category=@category,
Price=@price,
Instock=@instock,
[Count]=@count,
DateUpdate=@DateUpdate,
[Description]=@description  
  
where ID=@id
 
 
end



else

begin

INSERT INTO [DBT] (ID,ProductName,Category,Price,Instock,[Count],DateUpdate,[Description])
VALUES (@id,@prod,@category,@price,@instock,@count,@DateUpdate,@description)
 
 end
Posted

You need to declare ID(it will need to be named something else though) and change that line to this:
DECLARE @secondID varchar(max)

Set @secondID = Select ID FROM table WHERE ID = @id

IF @id = @secondID
   BEGIN
       --your code
END


"ID" will be the id column in your table and "table", of course is the table you are querying.
 
Share this answer
 
v5
Comments
[no name] 20-Dec-13 17:38pm    
but i want to compere the ID column value to the new insert value
Richard C Bishop 20-Dec-13 17:51pm    
See my update to the solution.
I do not know why you are trying to compare ID (which is not declared or instantiated) but I assume that you want to do an INSERT if the record with ID = @ID does not exist and an UPDATE if it does exist.

Below is how I would do it. Starting with Microsoft SQL Server 2008, there is a MERGE statement that could be used to cause the same result.

C#
ALTER PROC [dbo].[SqldataTable]
@id real,
@prod nvarchar(50),
@category varchar(50),
@price real,
@instock bit,
@count real,
@DateUpdate datetime,
@description nvarchar(max)
as


if  (select COUNT(*) from [DBT] where ID=@ID) > 0
begin
UPDATE  [DBT] 
set
ProductName=@prod,  
Category=@category,
Price=@price,
Instock=@instock,
[Count]=@count,
DateUpdate=@DateUpdate,
[Description]=@description  
where ID=@id
end
 
else
 
begin
INSERT INTO [DBT] (ID,ProductName,Category,Price,Instock,[Count],DateUpdate,[Description])
VALUES (@id,@prod,@category,@price,@instock,@count,@DateUpdate,@description)
end
 
Share this answer
 
v2

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