我试图了解一个查询是否比以下两个查询中的另一个查询有任何性能优势。感谢您帮助理解这一点。
- 这个查询一天会被调用几千到几十万次,可以是插入操作,也可以是更新操作。
--有一个CLUSTERED INDEX ON TYPE,ID ON XYZ table
查询1:
DECLARE @paramDef NVARCHAR(1000)
DECLARE @columnName NVARCHAR(100)
SET @paramDef = '@Type nvarchar(100), @Id INT'
SET @columnValue = 'testField'
SET @strSql =
N'IF NOT EXISTS(SELECT 1 FROM XYZ WITH (NOLOCK) WHERE Type = @Type AND ID = @Id)
BEGIN
.... insert into XYZ code
END
ELSE IF EXISTS (SELECT 1 FROM XYZ WITH (NOLOCK) WHERE Type = @ReferenceType AND Id = @Id
AND ' + @columnname + ' IS NULL)
BEGIN
.... update to XYZ code
END'
sp_executesql @strSql, @paramDef, @Type = 'abc', @Id = '123'
或查询2
DECLARE @paramDef NVARCHAR(100)
DECLARE @columnName NVARCHAR(100)
SET @paramDef = 'DECLARE @rowExists nvarchar(100), @columnValue nvarchar(100), @Type nvarchar(100), @Id INT'
SET @columnValue = 'testField'
SET @strSql =
N'SELECT @rowExists = 1, @columnValue=' + @columnname + ' FROM XYZ WITH (NOLOCK) WHERE Type = @Type AND ID = @Id
IF (@rowExists IS NULL) --row does not exists then insert
BEGIN
.... insert into XYZ code
END
ELSE IF (@rowExists = 1 and @columnValue IS NULL)
BEGIN
.... update to XYZ code
END'
sp_executesql @strSql, @paramDef, @Type = 'abc', @Id = '123', @rowExists = NULL, @columnValue = NULL
谢谢。