开发者

Optimization t-sql query

I'm newbie in t-sql, and I wonder why this query executes so long ? Is there any way to optimize this ??

update aggregateflags set value=@value where objecttype=@objecttype and objectcode=@objectcode and storagetype=@storagetype and value != 2 and type=@type 
IF @@ROWCOUNT=0 
Select * from aggregateflags where objecttype=@objecttype and objectcode=@objectcode and storagetype=@storagetype and value = 2 and type=@type  
IF @@ROWCOUNT=0  
insert into aggregateflags (objectcode,objecttype,value,type,storagetype) 
select @objectcode,@objecttype,@value,@type,@storagetype

@value int
@storagetype int
@ty开发者_如何学Pythonpe int
@objectcode nvarchar(100)
@objecttype int

There is not foreign key.


Would be easier to know the structure of aggregateflags table -- column types and indexes.

I would try:

  1. Check if there is matching index on table aggregateflags. If not find other matching or create one -- matching index for query is the most important thing (checking executing plan can help you).
  2. Add hints (if you can) WITH (ROWLOCK) for UPDATE and WITH (NOLOCK) for SELECT statement -- this help to avoid locking editing or reading data.
  3. Change SELECT * FROM aggregateflags... to SELECT TOP 1 1 FROM aggregateflags WITH (NOLOCK)... -- you don't need data -- you just need to check if row exists.


Make sure you have indexes defined on your columns. If this will not help, use "display execution plan" button in SQL studio and check what's wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜