Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: CREATE FUNCTION with declare variables inside

I would like to create a function in SQL Server.

In this function, I need to define some variables and then use it in the SELECT.

SQL looks like below:

CREATE FUNCTION [dbo].[MyFussnction]  
(
    @path [nvarchar](10)
)
RETURNS TABLE

BEGIN
    DECLARE @xx varchar(50);
    SET @xx = 'Windows%';
RETURN 
    SELECT * FROM MyTable WHERE DataPath LIKE @path AND XX LIKE @xx;
END

But, it is not able to be created and the error says:

Msg 102, Level 15, State 31, Procedure MyFussnction, Line 12 [Batch Start Line 0]
Incorrect syntax near 'BEGIN'.
like image 856
Howard Shane Avatar asked Sep 06 '25 01:09

Howard Shane


1 Answers

You need to define columns of table to return, then you can use declare, something like below

CREATE FUNCTION [dbo].[MyFussnction]  (  
@path [nvarchar](10)
)
RETURNS @Mytable TABLE 
(
    ID int PRIMARY KEY NOT NULL
    -- define other columns
)
AS
BEGIN
    DECLARE @xx varchar(50);
    SET @xx = 'Windows%';

    Insert into @Mytable
    SELECT Id FROM MyTable WHERE DataPath LIKE @path AND XX LIKE @xx;
  RETURN; 
END
like image 166
Reza Avatar answered Sep 09 '25 03:09

Reza