0

I'm trying to create this function which returns a table and has a table name as a parameter:

CREATE FUNCTION GetCostData(@CostTable VARCHAR(30))
RETURNS @H2 TABLE (
    Repairdate    datetime     NOT NULL,
    ReceivedDate  datetime     NOT NULL
)  
AS
BEGIN 
    INSERT INTO @H2(DataFactura, Data)
      SELECT R1.Repairdate, Max(H1.ReceivedDate) as ReceivedDate
        FROM @CostTable R1
        JOIN History H1 
        ON R1.VehicleID=H1.VehicleID 
        AND H1.ReceivedDate < R1.RepairDate
        GROUP BY R1.RepairDate;
    RETURN;
END;

But I get 'Must declare the scalar variable "@CostTable".' error. Why? How can I fix it?

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
milo2011
  • 339
  • 1
  • 9
  • 25

2 Answers2

1

You're missing the DECLARE @CostTable statement

Try this code:

CREATE FUNCTION GetCostData(@CostTable VARCHAR(30))
RETURNS @H2 TABLE (
    Repairdate    datetime     NOT NULL,
    ReceivedDate  datetime     NOT NULL
)

AS

BEGIN 
DECLARE @CostTable table (RepairDate datetime not null) 
    INSERT INTO @H2(DataFactura, Data)
      SELECT R1.Repairdate, Max(H1.ReceivedDate) as ReceivedDate
        FROM @CostTable R1
        JOIN History H1 
        ON R1.VehicleID=H1.VehicleID 
        AND H1.ReceivedDate < R1.RepairDate
        GROUP BY R1.RepairDate;
    RETURN;
END;

Hope this helps

Milica Medic Kiralj
  • 3,580
  • 31
  • 31
0

As you cannot use dynamic SQL in functions, it will be better to turn it into a stored procedure:

CREATE PROCEDURE GetCostData(@CostTable VARCHAR(30)) 
AS
BEGIN 
  DECLARE @sql NVARCHAR(1000) =
  N'SELECT R1.Repairdate, Max(H1.ReceivedDate) as ReceivedDate
    FROM ' + @CostTable + N'R1
    JOIN History H1 
    ON R1.VehicleID=H1.VehicleID 
    AND H1.ReceivedDate < R1.RepairDate
    GROUP BY R1.RepairDate'

    EXEC (@sql)
END

To use the result of this stored proc, you should insert the results into a temp table and then join to this temp table. See this SQL Fiddle.

create table table1(id int, Repairdate datetime)

insert into table1 values (1, getdate())

go

create procedure GetCostData
as
begin
  select getdate() as Repairdate, getdate() as ReceivedDate
end

go

create table #temp(Repairdate datetime, ReceivedDate datetime)

insert into #temp
exec getcostdata

select * from table1 t1
inner join #temp t
on cast(t1.Repairdate as date) = cast(t.Repairdate as date)
Szymon
  • 42,577
  • 16
  • 96
  • 114