1

I'm having trouble writing a function that will take a table variable as an input and return the total number of rows in that table.

Here is my try:

CREATE FUNCTION fTableRows( @table TABLE )
RETURNS INT AS
BEGIN
    RETURN( SELECT COUNT(*) FROM @table )
END
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mrgary
  • 43
  • 4

2 Answers2

2

If you do this in SQL server 2008 + you have use user defined data type - table. Good explanation can be found here: Pass table as parameter into SQL Udf

Community
  • 1
  • 1
Bogdan Bogdanov
  • 1,707
  • 2
  • 20
  • 31
2
CREATE FUNCTION getTableRows
(
    @TableName VARCHAR(30)
)
RETURNS INT AS
BEGIN
    RETURN( SELECT COUNT(*) FROM @TableName)
END
Digital Alchemist
  • 2,324
  • 1
  • 15
  • 17
  • 2
    I like this approach much better. The function should definitely accept "table name" instead of "table", if at all possible. IMHO... – paulsm4 Nov 05 '13 at 06:00