简体   繁体   English

如何通过使用sql server缓存记录数时减少临时表扫描的成本

[英]how can we reduce the cost of temp table scan while feching count of records by using sql server

here just i am trying to know count of records in the temp table and passing to another variable, so that it was showing in the execution plan table scan about 100 % 在这里,我只是想知道临时表中的记录数并传递给另一个变量,因此它在执行计划表扫描中显示了大约100%

please find the below query which i was doing 请找到我正在做的以下查询

DECLARE @tmpANHdr TABLE (
  hdrId          INT IDENTITY,
  CBFId          NVARCHAR(32),
  ACPT_REJ_FLAG  NVARCHAR(8),
  PROC_FILE_NAME NVARCHAR(50))

INSERT INTO @tmpANHdr
SELECT TOP 100 AHR_CB_FTS_FILE_ID,
               AHR_ACCT_REJ_FLAG,
               AHR_PROC_FILE_NAME
FROM   FTS_ACK_NAK_HEADER WITH (NOLOCK)
WHERE  AHR_FLAG IS NULL
        OR AHR_FLAG = 0

DECLARE @varRecordCount INT

SELECT @varRecordCount = Count(1)
FROM   @tmpANHdr

SET @varIndex = 1

IF( @varIndex <= @varRecordCount )
  BEGIN
      PRINT 'hi'
  END 

A scan on a table variable with no more than 100 rows is likely to be pretty cheap anyway. 无论如何,对不超过100行的表变量进行扫描可能很便宜。 The table scan operation might be costed at 100% of the plan for the statement but that is 100% of a pretty small number. 表扫描操作的费用可能是语句计划的100%,但这只是一个很小数目的100%。

You can avoid this cost entirely though by just looking at @@rowcount after the insert as below. 您可以完全避免此费用,尽管只需在插入后查看@@rowcount ,如下所示。

DECLARE @varRecordCount INT;

INSERT INTO @tmpANHdr
SELECT TOP 100 AHR_CB_FTS_FILE_ID,
               AHR_ACCT_REJ_FLAG,
               AHR_PROC_FILE_NAME
FROM   FTS_ACK_NAK_HEADER WITH (NOLOCK)
WHERE  AHR_FLAG IS NULL
        OR AHR_FLAG = 0

SET @varRecordCount = @@ROWCOUNT 

You could put a primary key (index) on the identity column and that might make it perform better: 您可以在标识列上放置一个主键(索引),这可能使其性能更好:

DECLARE @tmpANHdr TABLE (
  hdrId          INT IDENTITY PRIMARY KEY,
  CBFId          NVARCHAR(32),
  ACPT_REJ_FLAG  NVARCHAR(8),
  PROC_FILE_NAME NVARCHAR(50))

Also, do you end up using the table variable for anything else? 此外,您最终是否将table变量用于其他用途? Why not just do this? 为什么不这样做呢?

DECLARE @varRecordCount INT

SELECT @varRecordCount = Count(TOP 100 *)
FROM   FTS_ACK_NAK_HEADER WITH (NOLOCK)
WHERE  AHR_FLAG IS NULL
        OR AHR_FLAG = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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