Search notes:

SQL Server: Joining with table valued functions

In order to join with a table valued function that takes a parameter with a value from another table, the cross apply or outer apply method is needed.
The following example would cause a The multi-part identifier "s.num" could not be bound. error message if the table valued functions were joined with a cross join:
create function number_sequence(
            @start_ integer,
            @end_   integer,
            @step_  integer = 1
)
returns @seq table(num integer)
as begin

  declare @num integer = @start_;

  while @num <= @end_ begin
      insert into @seq values (@num);
      set @num = @num + @step_;
  end;

  return;

end;
go

create function num_times_string(
             @num    integer,
             @string varchar(10)
)
returns @ret table (string varchar(max))
as begin

  declare @cnt integer      =  1;
  declare @str varchar(max) = '';

  while @cnt <= @num begin
      set @str = @str + @string;
      insert into @ret values (@str);
      set @cnt = @cnt + 1;
  end;

  return;
end;
go


select
   *
from
   number_sequence (2, 8, 3) s    cross apply -- cross join -- The multi-part identifier "s.num" could not be bound.
   num_times_string(s.num, '*')
;
Github repository about-MSSQL, path: /t-sql/user-defined-functions/table-valued/join/cross-apply.sql

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758207106, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/databases/SQL-Server/T-SQL/user-defined-functions/table-valued/join(85): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78