Update+Increment else Insert
-
I'm not much of one with SQL, and I'm not sure if this is possible, but it seemed to me that it would be better to do it this way if it is than to split it into several queries. I'm making a page usage site for my ASP.NET page, and I want to store statistics for what browser is being used, which OS, etc. So I have a table with 2 fields: BrowserName and Sessions. I want to make a query that if the BrowserName exists, then it increments Sessions, otherwise it adds the BrowserName and sets Sessions to 1. Switching between Update/Insert in particular has left me clueless. Thanks in advance!
-
I'm not much of one with SQL, and I'm not sure if this is possible, but it seemed to me that it would be better to do it this way if it is than to split it into several queries. I'm making a page usage site for my ASP.NET page, and I want to store statistics for what browser is being used, which OS, etc. So I have a table with 2 fields: BrowserName and Sessions. I want to make a query that if the BrowserName exists, then it increments Sessions, otherwise it adds the BrowserName and sets Sessions to 1. Switching between Update/Insert in particular has left me clueless. Thanks in advance!
Hello, this is a sample stored procedure that does what you need, I assume that you use MS SQL This is just one way of doing it.
create proc InsertOrUpdateCount(@Browsername varchar)
as
update tablename
Set Sessions=session+1
where BrowserName = @Browsernameif @@rowcount=0 --no updates so the record does not exist
insert into tablename (BrowserName ,Sessions) values (@Browsername,1)Hesham A. Amin My blog