Thursday, February 9, 2012

A function to return number of records

Hello everyone,
I am trying to write a function that returns the number of records present in a table. But in this case i want to pass 'TABLENAME' as a parameter to this function and then retrieve numrecords henceforth.
This is how I'm currently trying to retrieve it -->

FUNCTION GetNumRecords(@.tablename as nvarchar(20))
return int as
begin
Declare @.numrecs as int
Set @.numrecs = (Select Count(*) from @.tablename)
return @.numrecs
end

I'm getting the following error:

--
Must declare the variable '@.tablename'.
--

But i am already passing @.tablename as a parameter to the function and I dont exactly understand where the problem is!! Why can't I use a local variable in a SELECT statement like this.

Any input is highly appreciated,
Thank you.use execute|||Or use:

SELECT @.numrecs = rowcnt FROM sysindexes
WHERE id = object_id(@.TableName)
AND indid in (0,1)

Each table must have at least 1 entry in sysindexes.
If the table has the clustered index, its indid will be 1.
If the table has no clustered, it will have a record with indid = 0.|||I'm afraid you're confusing SQL Server and Oracle syntax

Never use: DECLARE variable_name AS datatype
but instead: DECLARE variable_name datatype|||Refer to this link (http://www.sql-server-performance.com/forum/topic.asp?TOPIC_ID=280) to get the result.

No comments:

Post a Comment