简体   繁体   中英

SQL on-demand cache table (possibly using SQL MERGE)

I am working on implementing an on-demand SQL cache table for an application so I have

CacheTable with columns Type, Number, Value

Then I have a function called GetValue( Type, Number )

So I want to have a function that does the following

If ( CacheTable contains Type, Number) then return value Else call GetValue( Type, Number) and put that value into CacheTable and return the Value

Does anyone know the most elegant way to do this?

I was thinking of using a SQL merge.

Not sure how elegant one can get, but we might do it just the way you describe. Query the database

select Value from Tab1 where Type=@type and Number=@num

and if no rows are returned, compute the value, then store it in the database for next time. However, if the "compute the value" requires the database itself, and we can compute it in the database, then we can do the whole cycle with one database round trip -- more 'elegant' perhaps but faster at least than 3 round trips (lookup, compute, store).

declare @val int
select @val=Value from Tab1 where Type=@type and Number=@num
if @@ROWCOUNT=0 BEGIN
  exec compute_val @type,@num,@val OUTPUT
  insert into Tab1 values (@type,@num,@val)
END
SELECT @val[Value]--return

The only use for SQL Merge is if you think there may be concurrent users and the number is inserted between above select and insert, giving an error on the insert. I'd just catch the error and skip the insert (as we can assume the value won't be different by definition).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM