我的环境是 windows2008+ mssql2005
下面这句语句有没有优化的地方,update 和 insert 的时候要不要加上lock?
我开始是在程序中Exists后,在调用insert或者update,但是在数据库中 发现有相同索引([AS_Type] = @AS_Type and [C_ID] = @C_ID) 的数据.
为什么一开始没有用到这个存取过程,是因为有时候会碰到第一次执行这个存取过程的时候是update 那么第二次执行insert的时候 ,速度明显变慢的事件, 这是为什么,怎么避免?
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Alarm_Status_tbl_AddOrUpdateStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Alarm_Status_tbl_AddOrUpdateStatus
GO
------------------------------------
--用途:有数据就更新, 没有数据增加一条记录
--项目名称:
--说明:
--时间:2012/12/3 16:16:19
------------------------------------
CREATE PROCEDURE Alarm_Status_tbl_AddOrUpdateStatus
@AS_Type int,
@C_ID int,
@IsValid bit,
@IsUsed bit,
@UpdateTime datetime
AS
Begin
DECLARE @isok int
Begin Try
Begin Transaction
UPDATE [Alarm_Status_tbl] SET
[IsValid] = @IsValid,[IsUsed] = @IsUsed,[UpdateTime] = @UpdateTime
WHERE [AS_Type] = @AS_Type and [C_ID] = @C_ID
if @@rowcount=0
begin
INSERT INTO [Alarm_Status_tbl](
[AS_Type],[C_ID],[IsValid],[IsUsed],[UpdateTime]
)VALUES(
@AS_Type,@C_ID,@IsValid,@IsUsed,@UpdateTime
)
end
Commit Transaction
set @isok =1
End Try
Begin Catch
Rollback Transaction
set @isok = -1
print error_number()
print error_message()
print error_state()
print error_severity()
End Catch
return @isok
End
GO
------解决方案--------------------
[C_ID] + [AS_Type] 是否有索引?没有的话加上
------解决方案--------------------
如果在表[Alarm_Status_tbl]中,使用了数字型自增长的ID,而且表格数据量也很大的话,insert时候就会很慢。
------解决方案--------------------
是吗?
这是什么原理~------解决方案--------------------
我听老程序员的解释是,当主键是整数自整长数据加入的时候,内部机制会有重新排序,内部的排序并非使用该int型主键,而是使用uniqueidentifier,因为主键建立的时候会自动成为index。
所以大数据量表都建议使用uniqueidentifier作为主键。查询,添加删除数据整体效率更高。
------解决方案--------------------
受教~我去查查资料呵呵
------解决方案--------------------