行计数函数总是 returns NULL

Row count function always returns NULL

我创建了一个 SQL 函数,它实现了 COUNT(*) 操作的更快替代方法:

create function fast_row_count (@table_name varchar)
returns bigint 
as 
begin
declare @row_count int; 
set @row_count = 
(select sum(row_count) from sys.dm_db_partition_stats with (nolock) where object_id = object_id(@table_name));
return @row_count
end
go

执行时,总是returns一个NULL值。

select dbo.fast_row_count('tbl_calls')

但是,当使用硬编码值作为单独的批处理执行时,它可以正常工作:

    declare @row_count int;
    set @row_count = 
    (select sum(row_count) from sys.dm_db_partition_stats with (nolock) where object_id = object_id('tbl_calls'));
    print  @row_count
create function fast_row_count (@table_name varchar (max))

由于您定义的是 varchar 而未定义其长度,因此它给出 null

varchar [ ( n | 最大值 ) ]

Variable-length, non-Unicode string data. n defines the string length and can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size is the actual length of the data entered + 2 bytes. The ISO synonyms for varchar are char varying or character varying.

备注

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified when using the CAST and CONVERT functions, the default length is 30.

了解更多信息

https://msdn.microsoft.com/en-IN/library/ms176089.aspx