1

I have this script that executes, but I need it to take a user input instead of the setting the variable for @lastName.

CREATE FUNCTION displayCount() RETURNS INT
AS
BEGIN
    DECLARE @number INT, @lastName VARCHAR(40);
    SET @lastName = 'Ferrier';

    SELECT @number = COUNT(*) FROM Person.Person 
    WHERE LastName = @lastName;
    RETURN @number;
END   
GO

SELECT dbo.displayCount() AS howMany

I tried to mess with what I thought would work, but doesn't. I am getting and error

'Procedure or function dbo.diplayCount has too many arguments'

I'm sure it's something simple and with me being SO NEW, I can't see it. Thanks for the help!!

CREATE FUNCTION displayCount(@lastName VARCHAR(40)) RETURNS INT
AS
BEGIN
    DECLARE @number INT;   
    SELECT @number = COUNT(*) FROM Person.Person 
    WHERE LastName = @lastName;
    RETURN @number;
END   
GO

SELECT dbo.displayCount('Ferrier') as howMany
2
  • are you using SQL Server Management Studio? Commented Sep 12, 2018 at 0:06
  • yes I am using SQL Server Management Commented Sep 12, 2018 at 0:10

2 Answers 2

1

Your function looks so good, But I guess you need to use ALTER instead of CREATE because the function already exists in the DB.

you need to modify rather than create.

ALTER FUNCTION displayCount(@lastName VARCHAR(40)) RETURNS INT
AS
BEGIN
    DECLARE @number INT;   
    SELECT @number = COUNT(*) FROM Person.Person 
    WHERE LastName = @lastName;
    RETURN @number;
END  

GO

SELECT dbo.displayCount('Ferrier') as howMany
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry that was just a typo when typing the question
Yeah, I realized that at the same time. I hate being new, but it's a learning experience.
0

In SSMS, expand [your database] > Programmability Folder > Functions folder > Table-valued Functions > Right click > New Inline Table-valued Function....

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      
-- Create date: 
-- Description: 
-- =============================================
CREATE FUNCTION displayCount
(   
    @lastName   varchar(40)
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT COUNT(*) AS howMany
    FROM Person.Person 
    WHERE LastName = @lastName
)
GO

Then call it by

SELECT howMany FROM dbo.displayCount('Ferrier')

2 Comments

Why have you chosen to change from the OP's scalar function to table-valued function? Either one can accept parameters.
Thanks HABO, more like a hindsight on my part of not knowing the use of scalar functions. I've learned something new.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.