Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Error: A RETURN statement with a return value cannot be used in this context

I am just trying to create a function that returns a select statement, but it gives the error:

A RETURN statement with a return value cannot be used in this context.

This is my code:

CREATE FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS TABLE
AS
BEGIN
RETURN(
 SELECT * FROM View_sls
)

Please let me know the solution

like image 654
HOY Avatar asked Jun 05 '13 12:06

HOY


2 Answers

Two things:

  • you need to define the structure of the table you want to return
  • you need to add data into that table

Then you can call RETURN; to return that table's data to the caller.

So you need something like this:

CREATE FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS @returnTable TABLE 
                     (ContactID int PRIMARY KEY NOT NULL, 
                      FirstName nvarchar(50) NULL, 
                      LastName nvarchar(50) NULL, 
                      JobTitle nvarchar(50) NULL, 
                      ContactType nvarchar(50) NULL)
AS 
BEGIN
    INSERT INTO @returnTable
        SELECT ContactID, FirstName, LastName, JobTitle, ContactType
        FROM dbo.View_sls

    RETURN;
END 
like image 191
marc_s Avatar answered Sep 21 '22 16:09

marc_s


Wrong syntax, that's all. You don't need BEGIN when you have an "inline table-valued function"

See CREATE FUNCTION and example B

CREATE FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS TABLE
AS
RETURN
(
 SELECT * FROM View_sls
);
GO
like image 44
gbn Avatar answered Sep 21 '22 16:09

gbn