I am trying to create a table-valued function in SQL Server. My issue is that I can't find the right syntax for the SQL. I keep getting errors. I don't know if it is possible to use an execute() method in a table-valued function. I have tried declaring and setting the variables and also using the execute method in an oridinary sql query and it works.
My SQL:
CREATE FUNCTION SortRoutePartByDay
(
@date datetime
)
RETURNS TABLE
AS
Begin
declare @cmdtext varchar(max)
declare @Daynameofweek varchar(10)
set @Daynameofweek = datename(weekday, @date)
set @cmdtext = 'select * from RoutePartPart where ' +@Daynameofweek+' =1';
RETURN
(
execute(@cmdtext)
)
GO
My error so far is:
Msg 156, Level 15, State 1, Procedure SortRoutePartByDay, Line 21
Incorrect syntax near the keyword 'execute'.
Msg 102, Level 15, State 1, Procedure SortRoutePartByDay, Line 23
Incorrect syntax near ')'.
RoutePartPart DDL:
CREATE TABLE [dbo].[RoutePartPart](
[RouteID] [int] NOT NULL,
[RoutePartNo] [smallint] NOT NULL,
[RoutePartPartNo] [smallint] NOT NULL,
[PickupAreaGrpID] [int] NULL,
[DeliveryAreaGrpID] [int] NULL,
[Monday] [bit] NULL,
[Tuesday] [bit] NULL,
[Wednesday] [bit] NULL,
[Thursday] [bit] NULL,
[Friday] [bit] NULL,
[Saturday] [bit] NULL,
[Sunday] [bit] NULL,
[Pickup] [bit] NULL,
[Delivery] [bit] NULL,
[Types] [varchar](10) NULL
) ON [PRIMARY]